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_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/test/test_file_util.h"
26 #include "base/threading/sequenced_worker_pool.h"
27 #include "base/time/time.h"
28 #include "base/values.h"
29 #include "chrome/app/chrome_command_ids.h"
30 #include "chrome/browser/autocomplete/autocomplete_controller.h"
31 #include "chrome/browser/background/background_contents_service.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
35 #include "chrome/browser/devtools/devtools_window_testing.h"
36 #include "chrome/browser/download/download_prefs.h"
37 #include "chrome/browser/extensions/api/messaging/message_service.h"
38 #include "chrome/browser/extensions/crx_installer.h"
39 #include "chrome/browser/extensions/extension_management_constants.h"
40 #include "chrome/browser/extensions/extension_management_test_util.h"
41 #include "chrome/browser/extensions/extension_service.h"
42 #include "chrome/browser/extensions/shared_module_service.h"
43 #include "chrome/browser/extensions/unpacked_installer.h"
44 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
45 #include "chrome/browser/extensions/updater/extension_updater.h"
46 #include "chrome/browser/infobars/infobar_service.h"
47 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
48 #include "chrome/browser/media/media_stream_devices_controller.h"
49 #include "chrome/browser/metrics/variations/variations_service.h"
50 #include "chrome/browser/net/prediction_options.h"
51 #include "chrome/browser/net/ssl_config_service_manager.h"
52 #include "chrome/browser/net/url_request_mock_util.h"
53 #include "chrome/browser/plugins/plugin_prefs.h"
54 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
55 #include "chrome/browser/policy/profile_policy_connector.h"
56 #include "chrome/browser/policy/profile_policy_connector_factory.h"
57 #include "chrome/browser/prefs/session_startup_pref.h"
58 #include "chrome/browser/profiles/profile.h"
59 #include "chrome/browser/search/instant_service.h"
60 #include "chrome/browser/search/instant_service_factory.h"
61 #include "chrome/browser/search/search.h"
62 #include "chrome/browser/search_engines/template_url_service_factory.h"
63 #include "chrome/browser/translate/chrome_translate_client.h"
64 #include "chrome/browser/translate/cld_data_harness.h"
65 #include "chrome/browser/translate/cld_data_harness_factory.h"
66 #include "chrome/browser/translate/translate_service.h"
67 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
68 #include "chrome/browser/ui/browser.h"
69 #include "chrome/browser/ui/browser_commands.h"
70 #include "chrome/browser/ui/browser_list.h"
71 #include "chrome/browser/ui/browser_tabstrip.h"
72 #include "chrome/browser/ui/browser_window.h"
73 #include "chrome/browser/ui/host_desktop.h"
74 #include "chrome/browser/ui/location_bar/location_bar.h"
75 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
76 #include "chrome/browser/ui/omnibox/omnibox_view.h"
77 #include "chrome/browser/ui/tabs/tab_strip_model.h"
78 #include "chrome/common/chrome_paths.h"
79 #include "chrome/common/chrome_switches.h"
80 #include "chrome/common/extensions/extension_constants.h"
81 #include "chrome/common/extensions/features/feature_channel.h"
82 #include "chrome/common/pref_names.h"
83 #include "chrome/common/url_constants.h"
84 #include "chrome/grit/generated_resources.h"
85 #include "chrome/test/base/in_process_browser_test.h"
86 #include "chrome/test/base/test_switches.h"
87 #include "chrome/test/base/ui_test_utils.h"
88 #include "components/content_settings/core/common/content_settings.h"
89 #include "components/content_settings/core/common/content_settings_pattern.h"
90 #include "components/infobars/core/infobar.h"
91 #include "components/policy/core/browser/browser_policy_connector.h"
92 #include "components/policy/core/common/external_data_fetcher.h"
93 #include "components/policy/core/common/mock_configuration_policy_provider.h"
94 #include "components/policy/core/common/policy_map.h"
95 #include "components/policy/core/common/policy_pref_names.h"
96 #include "components/policy/core/common/policy_service.h"
97 #include "components/policy/core/common/policy_service_impl.h"
98 #include "components/search_engines/template_url.h"
99 #include "components/search_engines/template_url_service.h"
100 #include "components/translate/core/browser/language_state.h"
101 #include "components/translate/core/browser/translate_infobar_delegate.h"
102 #include "content/public/browser/browser_child_process_host_iterator.h"
103 #include "content/public/browser/browser_context.h"
104 #include "content/public/browser/browser_thread.h"
105 #include "content/public/browser/child_process_data.h"
106 #include "content/public/browser/download_item.h"
107 #include "content/public/browser/download_manager.h"
108 #include "content/public/browser/gpu_data_manager.h"
109 #include "content/public/browser/notification_details.h"
110 #include "content/public/browser/notification_observer.h"
111 #include "content/public/browser/notification_registrar.h"
112 #include "content/public/browser/notification_service.h"
113 #include "content/public/browser/notification_source.h"
114 #include "content/public/browser/notification_types.h"
115 #include "content/public/browser/plugin_service.h"
116 #include "content/public/browser/render_process_host.h"
117 #include "content/public/browser/render_view_host.h"
118 #include "content/public/browser/web_contents.h"
119 #include "content/public/common/content_constants.h"
120 #include "content/public/common/content_paths.h"
121 #include "content/public/common/process_type.h"
122 #include "content/public/common/result_codes.h"
123 #include "content/public/common/url_constants.h"
124 #include "content/public/common/webplugininfo.h"
125 #include "content/public/test/browser_test_utils.h"
126 #include "content/public/test/download_test_observer.h"
127 #include "content/public/test/mock_notification_observer.h"
128 #include "content/public/test/test_navigation_observer.h"
129 #include "content/public/test/test_utils.h"
130 #include "extensions/browser/extension_host.h"
131 #include "extensions/browser/extension_prefs.h"
132 #include "extensions/browser/extension_registry.h"
133 #include "extensions/browser/extension_system.h"
134 #include "extensions/browser/process_manager.h"
135 #include "extensions/browser/test_extension_registry_observer.h"
136 #include "extensions/browser/uninstall_reason.h"
137 #include "extensions/common/constants.h"
138 #include "extensions/common/extension.h"
139 #include "extensions/common/extension_set.h"
140 #include "extensions/common/manifest_handlers/shared_module_info.h"
141 #include "net/base/net_errors.h"
142 #include "net/base/net_util.h"
143 #include "net/base/url_util.h"
144 #include "net/http/http_stream_factory.h"
145 #include "net/ssl/ssl_config.h"
146 #include "net/ssl/ssl_config_service.h"
147 #include "net/test/url_request/url_request_failed_job.h"
148 #include "net/test/url_request/url_request_mock_http_job.h"
149 #include "net/url_request/url_request.h"
150 #include "net/url_request/url_request_filter.h"
151 #include "policy/policy_constants.h"
152 #include "testing/gmock/include/gmock/gmock.h"
153 #include "testing/gtest/include/gtest/gtest.h"
154 #include "third_party/WebKit/public/web/WebInputEvent.h"
155 #include "ui/base/l10n/l10n_util.h"
156 #include "ui/base/page_transition_types.h"
157 #include "ui/base/resource/resource_bundle.h"
158 #include "url/gurl.h"
160 #if defined(OS_CHROMEOS)
161 #include "ash/accelerators/accelerator_controller.h"
162 #include "ash/accelerators/accelerator_table.h"
163 #include "ash/shell.h"
164 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
165 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
166 #include "chrome/browser/profiles/profile_manager.h"
167 #include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
168 #include "chromeos/audio/cras_audio_handler.h"
169 #include "ui/chromeos/accessibility_types.h"
170 #include "ui/keyboard/keyboard_util.h"
171 #include "ui/snapshot/screenshot_grabber.h"
174 #if !defined(OS_MACOSX)
175 #include "base/basictypes.h"
176 #include "base/compiler_specific.h"
177 #include "chrome/browser/ui/extensions/app_launch_params.h"
178 #include "chrome/browser/ui/extensions/application_launch.h"
179 #include "extensions/browser/app_window/app_window.h"
180 #include "extensions/browser/app_window/app_window_registry.h"
181 #include "extensions/browser/app_window/native_app_window.h"
182 #include "ui/base/window_open_disposition.h"
185 using content::BrowserThread
;
186 using net::URLRequestMockHTTPJob
;
188 using testing::Return
;
195 #if defined(OS_CHROMEOS)
196 const int kOneHourInMs
= 60 * 60 * 1000;
197 const int kThreeHoursInMs
= 180 * 60 * 1000;
200 const char kURL
[] = "http://example.com";
201 const char kCookieValue
[] = "converted=true";
202 // Assigned to Philip J. Fry to fix eventually.
203 const char kCookieOptions
[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
205 const base::FilePath::CharType kTestExtensionsDir
[] =
206 FILE_PATH_LITERAL("extensions");
207 const base::FilePath::CharType kGoodCrxName
[] = FILE_PATH_LITERAL("good.crx");
208 const base::FilePath::CharType kAdBlockCrxName
[] =
209 FILE_PATH_LITERAL("adblock.crx");
210 const base::FilePath::CharType kHostedAppCrxName
[] =
211 FILE_PATH_LITERAL("hosted_app.crx");
213 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
214 const char kAdBlockCrxId
[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
215 const char kHostedAppCrxId
[] = "kbmnembihfiondgfjekmnmcbddelicoi";
217 const base::FilePath::CharType kGood2CrxManifestName
[] =
218 FILE_PATH_LITERAL("good2_update_manifest.xml");
219 const base::FilePath::CharType kGoodV1CrxManifestName
[] =
220 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
221 const base::FilePath::CharType kGoodV1CrxName
[] =
222 FILE_PATH_LITERAL("good_v1.crx");
223 const base::FilePath::CharType kGoodUnpackedExt
[] =
224 FILE_PATH_LITERAL("good_unpacked");
225 const base::FilePath::CharType kAppUnpackedExt
[] =
226 FILE_PATH_LITERAL("app");
228 #if !defined(OS_MACOSX)
229 const base::FilePath::CharType kUnpackedFullscreenAppName
[] =
230 FILE_PATH_LITERAL("fullscreen_app");
231 #endif // !defined(OS_MACOSX)
233 // Filters requests to the hosts in |urls| and redirects them to the test data
234 // dir through URLRequestMockHTTPJobs.
235 void RedirectHostsToTestData(const char* const urls
[], size_t size
) {
236 // Map the given hosts to the test data dir.
237 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
238 base::FilePath base_path
;
239 PathService::Get(chrome::DIR_TEST_DATA
, &base_path
);
240 for (size_t i
= 0; i
< size
; ++i
) {
241 const GURL
url(urls
[i
]);
242 EXPECT_TRUE(url
.is_valid());
243 filter
->AddUrlInterceptor(url
,
244 URLRequestMockHTTPJob::CreateInterceptor(
245 base_path
, BrowserThread::GetBlockingPool()));
249 // Remove filters for requests to the hosts in |urls|.
250 void UndoRedirectHostsToTestData(const char* const urls
[], size_t size
) {
251 // Map the given hosts to the test data dir.
252 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
253 for (size_t i
= 0; i
< size
; ++i
) {
254 const GURL
url(urls
[i
]);
255 EXPECT_TRUE(url
.is_valid());
256 filter
->RemoveUrlHandler(url
);
260 // Fails requests using ERR_CONNECTION_RESET.
261 net::URLRequestJob
* FailedJobFactory(
262 net::URLRequest
* request
,
263 net::NetworkDelegate
* network_delegate
,
264 const std::string
& scheme
) {
265 return new net::URLRequestFailedJob(
266 request
, network_delegate
, net::ERR_CONNECTION_RESET
);
269 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
270 class MakeRequestFail
{
272 // Sets up the filter on IO thread such that requests to |host| fail.
273 explicit MakeRequestFail(const std::string
& host
) : host_(host
) {
274 BrowserThread::PostTaskAndReply(
275 BrowserThread::IO
, FROM_HERE
,
276 base::Bind(MakeRequestFailOnIO
, host_
),
277 base::MessageLoop::QuitClosure());
278 content::RunMessageLoop();
281 BrowserThread::PostTaskAndReply(
282 BrowserThread::IO
, FROM_HERE
,
283 base::Bind(UndoMakeRequestFailOnIO
, host_
),
284 base::MessageLoop::QuitClosure());
285 content::RunMessageLoop();
289 // Filters requests to the |host| such that they fail. Run on IO thread.
290 static void MakeRequestFailOnIO(const std::string
& host
) {
291 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
292 filter
->AddHostnameHandler("http", host
, &FailedJobFactory
);
293 filter
->AddHostnameHandler("https", host
, &FailedJobFactory
);
296 // Remove filters for requests to the |host|. Run on IO thread.
297 static void UndoMakeRequestFailOnIO(const std::string
& host
) {
298 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
299 filter
->RemoveHostnameHandler("http", host
);
300 filter
->RemoveHostnameHandler("https", host
);
303 const std::string host_
;
306 // Verifies that the given url |spec| can be opened. This assumes that |spec|
307 // points at empty.html in the test data dir.
308 void CheckCanOpenURL(Browser
* browser
, const char* spec
) {
310 ui_test_utils::NavigateToURL(browser
, url
);
311 content::WebContents
* contents
=
312 browser
->tab_strip_model()->GetActiveWebContents();
313 EXPECT_EQ(url
, contents
->GetURL());
314 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
315 base::string16 title
=
316 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
317 EXPECT_NE(title
, contents
->GetTitle());
320 // Verifies that access to the given url |spec| is blocked.
321 void CheckURLIsBlocked(Browser
* browser
, const char* spec
) {
323 ui_test_utils::NavigateToURL(browser
, url
);
324 content::WebContents
* contents
=
325 browser
->tab_strip_model()->GetActiveWebContents();
326 EXPECT_EQ(url
, contents
->GetURL());
327 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
328 base::string16 title
=
329 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
330 EXPECT_EQ(title
, contents
->GetTitle());
332 // Verify that the expected error page is being displayed.
334 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
336 "var textContent = document.body.textContent;"
337 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
338 "domAutomationController.send(hasError);",
343 // Downloads a file named |file| and expects it to be saved to |dir|, which
345 void DownloadAndVerifyFile(
346 Browser
* browser
, const base::FilePath
& dir
, const base::FilePath
& file
) {
347 content::DownloadManager
* download_manager
=
348 content::BrowserContext::GetDownloadManager(browser
->profile());
349 content::DownloadTestObserverTerminal
observer(
351 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
352 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
353 base::FilePath downloaded
= dir
.Append(file
);
354 EXPECT_FALSE(base::PathExists(downloaded
));
355 ui_test_utils::NavigateToURL(browser
, url
);
356 observer
.WaitForFinished();
358 1u, observer
.NumDownloadsSeenInState(content::DownloadItem::COMPLETE
));
359 EXPECT_TRUE(base::PathExists(downloaded
));
360 base::FileEnumerator
enumerator(dir
, false, base::FileEnumerator::FILES
);
361 EXPECT_EQ(file
, enumerator
.Next().BaseName());
362 EXPECT_EQ(base::FilePath(), enumerator
.Next());
365 #if defined(OS_CHROMEOS)
366 int CountScreenshots() {
367 DownloadPrefs
* download_prefs
= DownloadPrefs::FromBrowserContext(
368 ProfileManager::GetActiveUserProfile());
369 base::FileEnumerator
enumerator(download_prefs
->DownloadPath(),
370 false, base::FileEnumerator::FILES
,
373 while (!enumerator
.Next().empty())
379 // Checks if WebGL is enabled in the given WebContents.
380 bool IsWebGLEnabled(content::WebContents
* contents
) {
382 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
384 "var canvas = document.createElement('canvas');"
385 "var context = canvas.getContext('webgl');"
386 "domAutomationController.send(context != null);",
391 bool IsJavascriptEnabled(content::WebContents
* contents
) {
392 scoped_ptr
<base::Value
> value
= content::ExecuteScriptAndGetValue(
393 contents
->GetMainFrame(), "123");
395 if (!value
->GetAsInteger(&result
))
396 EXPECT_EQ(base::Value::TYPE_NULL
, value
->GetType());
397 return result
== 123;
400 bool IsNetworkPredictionEnabled(PrefService
* prefs
) {
401 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs
);
404 void CopyPluginListAndQuit(std::vector
<content::WebPluginInfo
>* out
,
405 const std::vector
<content::WebPluginInfo
>& in
) {
407 base::MessageLoop::current()->QuitWhenIdle();
411 void CopyValueAndQuit(T
* out
, T in
) {
413 base::MessageLoop::current()->QuitWhenIdle();
416 void GetPluginList(std::vector
<content::WebPluginInfo
>* plugins
) {
417 content::PluginService
* service
= content::PluginService::GetInstance();
418 service
->GetPlugins(base::Bind(CopyPluginListAndQuit
, plugins
));
419 content::RunMessageLoop();
422 const content::WebPluginInfo
* GetFlashPlugin(
423 const std::vector
<content::WebPluginInfo
>& plugins
) {
424 const content::WebPluginInfo
* flash
= NULL
;
425 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
426 if (plugins
[i
].name
== base::ASCIIToUTF16(content::kFlashPluginName
)) {
431 #if defined(OFFICIAL_BUILD)
432 // Official builds bundle Flash.
436 LOG(INFO
) << "Test skipped because the Flash plugin couldn't be found.";
441 bool SetPluginEnabled(PluginPrefs
* plugin_prefs
,
442 const content::WebPluginInfo
* plugin
,
445 plugin_prefs
->EnablePlugin(enabled
, plugin
->path
,
446 base::Bind(CopyValueAndQuit
<bool>, &ok
));
447 content::RunMessageLoop();
451 int CountPluginsOnIOThread() {
453 for (content::BrowserChildProcessHostIterator iter
; !iter
.Done(); ++iter
) {
454 if (iter
.GetData().process_type
== content::PROCESS_TYPE_PLUGIN
||
455 iter
.GetData().process_type
== content::PROCESS_TYPE_PPAPI_PLUGIN
) {
464 BrowserThread::PostTaskAndReplyWithResult(
465 BrowserThread::IO
, FROM_HERE
,
466 base::Bind(CountPluginsOnIOThread
),
467 base::Bind(CopyValueAndQuit
<int>, &count
));
468 content::RunMessageLoop();
473 void FlushBlacklistPolicy() {
474 // Updates of the URLBlacklist are done on IO, after building the blacklist
475 // on the blocking pool, which is initiated from IO.
476 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
477 BrowserThread::GetBlockingPool()->FlushForTesting();
478 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
481 bool ContainsVisibleElement(content::WebContents
* contents
,
482 const std::string
& id
) {
484 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
486 "var elem = document.getElementById('" + id
+ "');"
487 "domAutomationController.send(!!elem && !elem.hidden);",
492 #if defined(OS_CHROMEOS)
493 class TestAudioObserver
: public chromeos::CrasAudioHandler::AudioObserver
{
495 TestAudioObserver() : output_mute_changed_count_(0) {
498 int output_mute_changed_count() const {
499 return output_mute_changed_count_
;
502 ~TestAudioObserver() override
{}
505 // chromeos::CrasAudioHandler::AudioObserver overrides.
506 void OnOutputMuteChanged() override
{ ++output_mute_changed_count_
; }
509 int output_mute_changed_count_
;
511 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver
);
515 // This class waits until either a load stops or the WebContents is destroyed.
516 class WebContentsLoadedOrDestroyedWatcher
517 : public content::WebContentsObserver
{
519 explicit WebContentsLoadedOrDestroyedWatcher(
520 content::WebContents
* web_contents
);
521 ~WebContentsLoadedOrDestroyedWatcher() override
;
523 // Waits until the WebContents's load is done or until it is destroyed.
526 // Overridden WebContentsObserver methods.
527 void WebContentsDestroyed() override
;
528 void DidStopLoading(content::RenderViewHost
* render_view_host
) override
;
531 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
533 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher
);
536 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
537 content::WebContents
* web_contents
)
538 : content::WebContentsObserver(web_contents
),
539 message_loop_runner_(new content::MessageLoopRunner
) {
542 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
544 void WebContentsLoadedOrDestroyedWatcher::Wait() {
545 message_loop_runner_
->Run();
548 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
549 message_loop_runner_
->Quit();
552 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
553 content::RenderViewHost
* render_view_host
) {
554 message_loop_runner_
->Quit();
557 #if !defined(OS_MACOSX)
559 // Observer used to wait for the creation of a new app window.
560 class TestAddAppWindowObserver
561 : public extensions::AppWindowRegistry::Observer
{
563 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry
* registry
);
564 ~TestAddAppWindowObserver() override
;
566 // extensions::AppWindowRegistry::Observer:
567 void OnAppWindowAdded(extensions::AppWindow
* app_window
) override
;
569 extensions::AppWindow
* WaitForAppWindow();
572 extensions::AppWindowRegistry
* registry_
; // Not owned.
573 extensions::AppWindow
* window_
; // Not owned.
574 base::RunLoop run_loop_
;
576 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver
);
579 TestAddAppWindowObserver::TestAddAppWindowObserver(
580 extensions::AppWindowRegistry
* registry
)
581 : registry_(registry
), window_(NULL
) {
582 registry_
->AddObserver(this);
585 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
586 registry_
->RemoveObserver(this);
589 void TestAddAppWindowObserver::OnAppWindowAdded(
590 extensions::AppWindow
* app_window
) {
591 window_
= app_window
;
595 extensions::AppWindow
* TestAddAppWindowObserver::WaitForAppWindow() {
604 class PolicyTest
: public InProcessBrowserTest
{
607 ~PolicyTest() override
{}
609 void SetUp() override
{
610 test_extension_cache_
.reset(new extensions::ExtensionCacheFake());
611 InProcessBrowserTest::SetUp();
614 void SetUpInProcessBrowserTestFixture() override
{
615 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
616 EXPECT_CALL(provider_
, IsInitializationComplete(_
))
617 .WillRepeatedly(Return(true));
618 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_
);
621 void SetUpOnMainThread() override
{
622 BrowserThread::PostTask(
623 BrowserThread::IO
, FROM_HERE
,
624 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled
, true));
625 if (extension_service()->updater()) {
626 extension_service()->updater()->SetExtensionCacheForTesting(
627 test_extension_cache_
.get());
631 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
632 // instead of chrome::DIR_TEST_DATA.
633 void ServeContentTestData() {
634 base::FilePath root_http
;
635 PathService::Get(content::DIR_TEST_DATA
, &root_http
);
636 BrowserThread::PostTaskAndReply(
637 BrowserThread::IO
, FROM_HERE
,
638 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers
, root_http
,
639 make_scoped_refptr(BrowserThread::GetBlockingPool())),
640 base::MessageLoop::current()->QuitWhenIdleClosure());
641 content::RunMessageLoop();
644 void SetScreenshotPolicy(bool enabled
) {
646 policies
.Set(key::kDisableScreenshots
,
647 POLICY_LEVEL_MANDATORY
,
649 new base::FundamentalValue(!enabled
),
651 UpdateProviderPolicy(policies
);
654 #if defined(OS_CHROMEOS)
655 class QuitMessageLoopAfterScreenshot
: public ui::ScreenshotGrabberObserver
{
657 void OnScreenshotCompleted(
658 ScreenshotGrabberObserver::Result screenshot_result
,
659 const base::FilePath
& screenshot_path
) override
{
660 BrowserThread::PostTaskAndReply(BrowserThread::IO
,
662 base::Bind(base::DoNothing
),
663 base::MessageLoop::QuitClosure());
666 ~QuitMessageLoopAfterScreenshot() override
{}
669 void TestScreenshotFile(bool enabled
) {
670 // AddObserver is an ash-specific method, so just replace the screenshot
671 // grabber with one we've created here.
672 scoped_ptr
<ChromeScreenshotGrabber
> chrome_screenshot_grabber(
673 new ChromeScreenshotGrabber
);
674 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
675 // is tied to the test instead.
676 chrome_screenshot_grabber
->screenshot_grabber()->AddObserver(&observer_
);
677 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
678 chrome_screenshot_grabber
.Pass());
680 SetScreenshotPolicy(enabled
);
681 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
682 ash::TAKE_SCREENSHOT
);
684 content::RunMessageLoop();
685 static_cast<ChromeScreenshotGrabber
*>(ash::Shell::GetInstance()
686 ->accelerator_controller()
687 ->screenshot_delegate())
688 ->screenshot_grabber()
689 ->RemoveObserver(&observer_
);
693 ExtensionService
* extension_service() {
694 extensions::ExtensionSystem
* system
=
695 extensions::ExtensionSystem::Get(browser()->profile());
696 return system
->extension_service();
699 const extensions::Extension
* InstallExtension(
700 const base::FilePath::StringType
& name
) {
701 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
702 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
703 scoped_refptr
<extensions::CrxInstaller
> installer
=
704 extensions::CrxInstaller::CreateSilent(extension_service());
705 installer
->set_allow_silent_install(true);
706 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
707 installer
->set_creation_flags(extensions::Extension::FROM_WEBSTORE
);
709 content::WindowedNotificationObserver
observer(
710 extensions::NOTIFICATION_CRX_INSTALLER_DONE
,
711 content::NotificationService::AllSources());
712 installer
->InstallCrx(extension_path
);
714 content::Details
<const extensions::Extension
> details
= observer
.details();
715 return details
.ptr();
718 const extensions::Extension
* LoadUnpackedExtension(
719 const base::FilePath::StringType
& name
, bool expect_success
) {
720 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
721 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
722 scoped_refptr
<extensions::UnpackedInstaller
> installer
=
723 extensions::UnpackedInstaller::Create(extension_service());
724 content::WindowedNotificationObserver
observer(
725 expect_success
? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
726 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR
,
727 content::NotificationService::AllSources());
728 installer
->Load(extension_path
);
731 extensions::ExtensionRegistry
* registry
=
732 extensions::ExtensionRegistry::Get(browser()->profile());
733 for (const scoped_refptr
<const extensions::Extension
>& extension
:
734 registry
->enabled_extensions()) {
735 if (extension
->path() == extension_path
)
736 return extension
.get();
741 void UninstallExtension(const std::string
& id
, bool expect_success
) {
742 content::WindowedNotificationObserver
observer(
744 ? extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
745 : extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
746 content::NotificationService::AllSources());
747 extension_service()->UninstallExtension(
749 extensions::UNINSTALL_REASON_FOR_TESTING
,
750 base::Bind(&base::DoNothing
),
755 void DisableExtension(const std::string
& id
) {
756 content::WindowedNotificationObserver
observer(
757 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
758 content::NotificationService::AllSources());
759 extension_service()->DisableExtension(id
,
760 extensions::Extension::DISABLE_NONE
);
764 void UpdateProviderPolicy(const PolicyMap
& policy
) {
765 provider_
.UpdateChromePolicy(policy
);
766 DCHECK(base::MessageLoop::current());
771 // Sends a mouse click at the given coordinates to the current renderer.
772 void PerformClick(int x
, int y
) {
773 content::WebContents
* contents
=
774 browser()->tab_strip_model()->GetActiveWebContents();
775 blink::WebMouseEvent click_event
;
776 click_event
.type
= blink::WebInputEvent::MouseDown
;
777 click_event
.button
= blink::WebMouseEvent::ButtonLeft
;
778 click_event
.clickCount
= 1;
781 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
782 click_event
.type
= blink::WebInputEvent::MouseUp
;
783 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
786 MockConfigurationPolicyProvider provider_
;
787 scoped_ptr
<extensions::ExtensionCacheFake
> test_extension_cache_
;
788 #if defined(OS_CHROMEOS)
789 QuitMessageLoopAfterScreenshot observer_
;
794 // This policy only exists on Windows.
796 // Sets the locale policy before the browser is started.
797 class LocalePolicyTest
: public PolicyTest
{
799 LocalePolicyTest() {}
800 virtual ~LocalePolicyTest() {}
802 virtual void SetUpInProcessBrowserTestFixture() override
{
803 PolicyTest::SetUpInProcessBrowserTestFixture();
805 policies
.Set(key::kApplicationLocaleValue
,
806 POLICY_LEVEL_MANDATORY
,
808 new base::StringValue("fr"),
810 provider_
.UpdateChromePolicy(policies
);
811 // The "en-US" ResourceBundle is always loaded before this step for tests,
812 // but in this test we want the browser to load the bundle as it
814 ResourceBundle::CleanupSharedInstance();
818 IN_PROC_BROWSER_TEST_F(LocalePolicyTest
, ApplicationLocaleValue
) {
819 // Verifies that the default locale can be overridden with policy.
820 EXPECT_EQ("fr", g_browser_process
->GetApplicationLocale());
821 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
822 base::string16 french_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
823 base::string16 title
;
824 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title
));
825 EXPECT_EQ(french_title
, title
);
827 // Make sure this is really French and differs from the English title.
829 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
830 EXPECT_EQ("en-US", loaded
);
831 base::string16 english_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
832 EXPECT_NE(french_title
, english_title
);
836 IN_PROC_BROWSER_TEST_F(PolicyTest
, BookmarkBarEnabled
) {
837 #if defined(OS_WIN) && defined(USE_ASH)
838 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
839 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
840 switches::kAshBrowserTests
))
844 // Verifies that the bookmarks bar can be forced to always or never show up.
846 // Test starts in about:blank.
847 PrefService
* prefs
= browser()->profile()->GetPrefs();
848 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
849 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
850 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
853 policies
.Set(key::kBookmarkBarEnabled
,
854 POLICY_LEVEL_MANDATORY
,
856 new base::FundamentalValue(true),
858 UpdateProviderPolicy(policies
);
859 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
860 EXPECT_TRUE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
861 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
863 // The NTP has special handling of the bookmark bar.
864 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
865 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
867 policies
.Set(key::kBookmarkBarEnabled
,
868 POLICY_LEVEL_MANDATORY
,
870 new base::FundamentalValue(false),
872 UpdateProviderPolicy(policies
);
873 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
874 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
875 // The bookmark bar is hidden in the NTP when disabled by policy.
876 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
879 UpdateProviderPolicy(policies
);
880 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
881 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
882 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
883 EXPECT_EQ(BookmarkBar::DETACHED
, browser()->bookmark_bar_state());
886 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_PRE_DefaultCookiesSetting
) {
887 // Verifies that cookies are deleted on shutdown. This test is split in 3
888 // parts because it spans 2 browser restarts.
890 Profile
* profile
= browser()->profile();
892 // No cookies at startup.
893 EXPECT_TRUE(content::GetCookies(profile
, url
).empty());
895 std::string value
= std::string(kCookieValue
) + std::string(kCookieOptions
);
896 EXPECT_TRUE(content::SetCookie(profile
, url
, value
));
897 // Verify it was set.
898 EXPECT_EQ(kCookieValue
, GetCookies(profile
, url
));
901 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_DefaultCookiesSetting
) {
902 // Verify that the cookie persists across restarts.
903 EXPECT_EQ(kCookieValue
, GetCookies(browser()->profile(), GURL(kURL
)));
904 // Now set the policy and the cookie should be gone after another restart.
906 policies
.Set(key::kDefaultCookiesSetting
,
907 POLICY_LEVEL_MANDATORY
,
909 new base::FundamentalValue(4),
911 UpdateProviderPolicy(policies
);
914 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultCookiesSetting
) {
915 // Verify that the cookie is gone.
916 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL
)).empty());
919 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultSearchProvider
) {
920 MakeRequestFail
make_request_fail("search.example");
922 // Verifies that a default search is made using the provider configured via
923 // policy. Also checks that default search can be completely disabled.
924 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
925 const std::string
kSearchURL("http://search.example/search?q={searchTerms}");
926 const std::string
kAlternateURL0(
927 "http://search.example/search#q={searchTerms}");
928 const std::string
kAlternateURL1("http://search.example/#q={searchTerms}");
929 const std::string
kSearchTermsReplacementKey("zekey");
930 const std::string
kImageURL("http://test.com/searchbyimage/upload");
931 const std::string
kImageURLPostParams(
932 "image_content=content,image_url=http://test.com/test.png");
933 const std::string
kNewTabURL("http://search.example/newtab");
935 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
936 browser()->profile());
937 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
938 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
939 ASSERT_TRUE(default_search
);
940 EXPECT_NE(kKeyword
, default_search
->keyword());
941 EXPECT_NE(kSearchURL
, default_search
->url());
943 default_search
->alternate_urls().size() == 2 &&
944 default_search
->alternate_urls()[0] == kAlternateURL0
&&
945 default_search
->alternate_urls()[1] == kAlternateURL1
&&
946 default_search
->search_terms_replacement_key() ==
947 kSearchTermsReplacementKey
&&
948 default_search
->image_url() == kImageURL
&&
949 default_search
->image_url_post_params() == kImageURLPostParams
&&
950 default_search
->new_tab_url() == kNewTabURL
);
952 // Override the default search provider using policies.
954 policies
.Set(key::kDefaultSearchProviderEnabled
,
955 POLICY_LEVEL_MANDATORY
,
957 new base::FundamentalValue(true),
959 policies
.Set(key::kDefaultSearchProviderKeyword
,
960 POLICY_LEVEL_MANDATORY
,
962 new base::StringValue(kKeyword
),
964 policies
.Set(key::kDefaultSearchProviderSearchURL
,
965 POLICY_LEVEL_MANDATORY
,
967 new base::StringValue(kSearchURL
),
969 base::ListValue
* alternate_urls
= new base::ListValue();
970 alternate_urls
->AppendString(kAlternateURL0
);
971 alternate_urls
->AppendString(kAlternateURL1
);
972 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
973 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
974 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
975 POLICY_LEVEL_MANDATORY
,
977 new base::StringValue(kSearchTermsReplacementKey
),
979 policies
.Set(key::kDefaultSearchProviderImageURL
,
980 POLICY_LEVEL_MANDATORY
,
982 new base::StringValue(kImageURL
),
984 policies
.Set(key::kDefaultSearchProviderImageURLPostParams
,
985 POLICY_LEVEL_MANDATORY
,
987 new base::StringValue(kImageURLPostParams
),
989 policies
.Set(key::kDefaultSearchProviderNewTabURL
,
990 POLICY_LEVEL_MANDATORY
,
992 new base::StringValue(kNewTabURL
),
994 UpdateProviderPolicy(policies
);
995 default_search
= service
->GetDefaultSearchProvider();
996 ASSERT_TRUE(default_search
);
997 EXPECT_EQ(kKeyword
, default_search
->keyword());
998 EXPECT_EQ(kSearchURL
, default_search
->url());
999 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1000 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1001 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1002 EXPECT_EQ(kSearchTermsReplacementKey
,
1003 default_search
->search_terms_replacement_key());
1004 EXPECT_EQ(kImageURL
, default_search
->image_url());
1005 EXPECT_EQ(kImageURLPostParams
, default_search
->image_url_post_params());
1006 EXPECT_EQ(kNewTabURL
, default_search
->new_tab_url());
1008 // Verify that searching from the omnibox uses kSearchURL.
1009 chrome::FocusLocationBar(browser());
1010 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1011 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "stuff to search for");
1012 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1013 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1014 content::WebContents
* web_contents
=
1015 browser()->tab_strip_model()->GetActiveWebContents();
1016 GURL
expected("http://search.example/search?q=stuff+to+search+for");
1017 EXPECT_EQ(expected
, web_contents
->GetURL());
1019 // Verify that searching from the omnibox can be disabled.
1020 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1021 policies
.Set(key::kDefaultSearchProviderEnabled
,
1022 POLICY_LEVEL_MANDATORY
,
1024 new base::FundamentalValue(false),
1026 EXPECT_TRUE(service
->GetDefaultSearchProvider());
1027 UpdateProviderPolicy(policies
);
1028 EXPECT_FALSE(service
->GetDefaultSearchProvider());
1029 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "should not work");
1030 // This means that submitting won't trigger any action.
1031 EXPECT_FALSE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1032 EXPECT_EQ(GURL(url::kAboutBlankURL
), web_contents
->GetURL());
1035 IN_PROC_BROWSER_TEST_F(PolicyTest
, PolicyPreprocessing
) {
1036 // Add an individual proxy policy value.
1038 policies
.Set(key::kProxyServerMode
,
1039 POLICY_LEVEL_MANDATORY
,
1041 new base::FundamentalValue(3),
1043 UpdateProviderPolicy(policies
);
1045 // It should be removed and replaced with a dictionary.
1047 scoped_ptr
<base::DictionaryValue
> expected_value(new base::DictionaryValue
);
1048 expected_value
->SetInteger(key::kProxyServerMode
, 3);
1049 expected
.Set(key::kProxySettings
,
1050 POLICY_LEVEL_MANDATORY
,
1052 expected_value
.release(),
1055 // Check both the browser and the profile.
1056 const PolicyMap
& actual_from_browser
=
1057 g_browser_process
->browser_policy_connector()
1058 ->GetPolicyService()
1059 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1060 EXPECT_TRUE(expected
.Equals(actual_from_browser
));
1061 const PolicyMap
& actual_from_profile
=
1062 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1064 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1065 EXPECT_TRUE(expected
.Equals(actual_from_profile
));
1068 IN_PROC_BROWSER_TEST_F(PolicyTest
, ForceSafeSearch
) {
1069 // Makes the requests fail since all we want to check is that the redirection
1070 // is done properly.
1071 MakeRequestFail
make_request_fail("google.com");
1073 // Verifies that requests to Google Search engine with the SafeSearch
1074 // enabled set the safe=active&ssui=on parameters at the end of the query.
1075 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1076 browser()->profile());
1077 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1079 // First check that nothing happens.
1080 content::TestNavigationObserver
no_safesearch_observer(
1081 browser()->tab_strip_model()->GetActiveWebContents());
1082 chrome::FocusLocationBar(browser());
1083 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1084 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
1085 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1086 no_safesearch_observer
.Wait();
1087 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1088 content::WebContents
* web_contents
=
1089 browser()->tab_strip_model()->GetActiveWebContents();
1090 GURL
expected_without("http://google.com/");
1091 EXPECT_EQ(expected_without
, web_contents
->GetURL());
1093 PrefService
* prefs
= browser()->profile()->GetPrefs();
1094 EXPECT_FALSE(prefs
->IsManagedPreference(prefs::kForceSafeSearch
));
1095 EXPECT_FALSE(prefs
->GetBoolean(prefs::kForceSafeSearch
));
1097 // Override the default SafeSearch setting using policies.
1099 policies
.Set(key::kForceSafeSearch
,
1100 POLICY_LEVEL_MANDATORY
,
1102 new base::FundamentalValue(true),
1104 UpdateProviderPolicy(policies
);
1106 EXPECT_TRUE(prefs
->IsManagedPreference(prefs::kForceSafeSearch
));
1107 EXPECT_TRUE(prefs
->GetBoolean(prefs::kForceSafeSearch
));
1109 content::TestNavigationObserver
safesearch_observer(
1110 browser()->tab_strip_model()->GetActiveWebContents());
1112 // Verify that searching from google.com works.
1113 chrome::FocusLocationBar(browser());
1114 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
1115 safesearch_observer
.Wait();
1116 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1117 web_contents
= browser()->tab_strip_model()->GetActiveWebContents();
1118 std::string
expected_url("http://google.com/?");
1119 expected_url
+= std::string(chrome::kSafeSearchSafeParameter
) + "&" +
1120 chrome::kSafeSearchSsuiParameter
;
1121 GURL
expected_with_parameters(expected_url
);
1122 EXPECT_EQ(expected_with_parameters
, web_contents
->GetURL());
1125 IN_PROC_BROWSER_TEST_F(PolicyTest
, ReplaceSearchTerms
) {
1126 MakeRequestFail
make_request_fail("search.example");
1128 chrome::EnableQueryExtractionForTesting();
1130 // Verifies that a default search is made using the provider configured via
1131 // policy. Also checks that default search can be completely disabled.
1132 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
1133 const std::string
kSearchURL("https://www.google.com/search?q={searchTerms}");
1134 const std::string
kInstantURL("http://does/not/exist");
1135 const std::string
kAlternateURL0(
1136 "https://www.google.com/search#q={searchTerms}");
1137 const std::string
kAlternateURL1("https://www.google.com/#q={searchTerms}");
1138 const std::string
kSearchTermsReplacementKey(
1139 "{google:instantExtendedEnabledKey}");
1141 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1142 browser()->profile());
1143 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1144 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1145 ASSERT_TRUE(default_search
);
1146 EXPECT_NE(kKeyword
, default_search
->keyword());
1147 EXPECT_NE(kSearchURL
, default_search
->url());
1148 EXPECT_NE(kInstantURL
, default_search
->instant_url());
1150 default_search
->alternate_urls().size() == 2 &&
1151 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1152 default_search
->alternate_urls()[1] == kAlternateURL1
);
1154 // Override the default search provider using policies.
1156 policies
.Set(key::kDefaultSearchProviderEnabled
,
1157 POLICY_LEVEL_MANDATORY
,
1159 new base::FundamentalValue(true),
1161 policies
.Set(key::kDefaultSearchProviderKeyword
,
1162 POLICY_LEVEL_MANDATORY
,
1164 new base::StringValue(kKeyword
),
1166 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1167 POLICY_LEVEL_MANDATORY
,
1169 new base::StringValue(kSearchURL
),
1171 policies
.Set(key::kDefaultSearchProviderInstantURL
,
1172 POLICY_LEVEL_MANDATORY
,
1174 new base::StringValue(kInstantURL
),
1176 base::ListValue
* alternate_urls
= new base::ListValue();
1177 alternate_urls
->AppendString(kAlternateURL0
);
1178 alternate_urls
->AppendString(kAlternateURL1
);
1179 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1180 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
1181 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1182 POLICY_LEVEL_MANDATORY
,
1184 new base::StringValue(kSearchTermsReplacementKey
),
1186 UpdateProviderPolicy(policies
);
1187 default_search
= service
->GetDefaultSearchProvider();
1188 ASSERT_TRUE(default_search
);
1189 EXPECT_EQ(kKeyword
, default_search
->keyword());
1190 EXPECT_EQ(kSearchURL
, default_search
->url());
1191 EXPECT_EQ(kInstantURL
, default_search
->instant_url());
1192 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1193 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1194 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1196 // Query terms replacement requires that the renderer process be a recognized
1197 // Instant renderer. Fake it.
1198 InstantService
* instant_service
=
1199 InstantServiceFactory::GetForProfile(browser()->profile());
1200 instant_service
->AddInstantProcess(browser()->tab_strip_model()->
1201 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1203 // Verify that searching from the omnibox does search term replacement with
1204 // first URL pattern.
1205 chrome::FocusLocationBar(browser());
1206 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1207 OmniboxView
* omnibox_view
= location_bar
->GetOmniboxView();
1208 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1209 "https://www.google.com/?espv=1#q=foobar");
1211 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1212 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1214 // Verify that not using espv=1 does not do search term replacement.
1215 chrome::FocusLocationBar(browser());
1216 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1217 "https://www.google.com/?q=foobar");
1219 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1220 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1221 omnibox_view
->GetText());
1223 // Verify that searching from the omnibox does search term replacement with
1224 // second URL pattern.
1225 chrome::FocusLocationBar(browser());
1226 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1227 "https://www.google.com/search?espv=1#q=banana");
1229 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1230 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view
->GetText());
1232 // Verify that searching from the omnibox does search term replacement with
1233 // standard search URL pattern.
1234 chrome::FocusLocationBar(browser());
1235 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1236 "https://www.google.com/search?q=tractor+parts&espv=1");
1238 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1239 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view
->GetText());
1241 // Verify that searching from the omnibox prioritizes hash over query.
1242 chrome::FocusLocationBar(browser());
1243 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1244 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1246 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1247 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1250 IN_PROC_BROWSER_TEST_F(PolicyTest
, Disable3DAPIs
) {
1251 // This test assumes Gpu access.
1252 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL
))
1255 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1256 // WebGL is enabled by default.
1257 content::WebContents
* contents
=
1258 browser()->tab_strip_model()->GetActiveWebContents();
1259 EXPECT_TRUE(IsWebGLEnabled(contents
));
1260 // Disable with a policy.
1262 policies
.Set(key::kDisable3DAPIs
,
1263 POLICY_LEVEL_MANDATORY
,
1265 new base::FundamentalValue(true),
1267 UpdateProviderPolicy(policies
);
1268 // Crash and reload the tab to get a new renderer.
1269 content::CrashTab(contents
);
1270 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1271 EXPECT_FALSE(IsWebGLEnabled(contents
));
1272 // Enable with a policy.
1273 policies
.Set(key::kDisable3DAPIs
,
1274 POLICY_LEVEL_MANDATORY
,
1276 new base::FundamentalValue(false),
1278 UpdateProviderPolicy(policies
);
1279 content::CrashTab(contents
);
1280 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1281 EXPECT_TRUE(IsWebGLEnabled(contents
));
1284 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableSpdy
) {
1285 // Verifies that SPDY can be disable by policy.
1286 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1288 policies
.Set(key::kDisableSpdy
,
1289 POLICY_LEVEL_MANDATORY
,
1291 new base::FundamentalValue(true),
1293 UpdateProviderPolicy(policies
);
1294 content::RunAllPendingInMessageLoop();
1295 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1296 // Verify that it can be force-enabled too.
1297 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy
, true);
1298 policies
.Set(key::kDisableSpdy
,
1299 POLICY_LEVEL_MANDATORY
,
1301 new base::FundamentalValue(false),
1303 UpdateProviderPolicy(policies
);
1304 content::RunAllPendingInMessageLoop();
1305 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1308 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPlugins
) {
1309 // Verifies that plugins can be forced to be disabled by policy.
1311 // Verify that the Flash plugin exists and that it can be enabled and disabled
1313 std::vector
<content::WebPluginInfo
> plugins
;
1314 GetPluginList(&plugins
);
1315 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1318 PluginPrefs
* plugin_prefs
=
1319 PluginPrefs::GetForProfile(browser()->profile()).get();
1320 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1321 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1322 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1323 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1324 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1326 // Now disable it with a policy.
1327 base::ListValue disabled_plugins
;
1328 disabled_plugins
.Append(new base::StringValue("*Flash*"));
1330 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1331 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1332 UpdateProviderPolicy(policies
);
1333 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1334 // The user shouldn't be able to enable it.
1335 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1336 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1339 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPluginsExceptions
) {
1340 // Verifies that plugins with an exception in the blacklist can be enabled.
1342 // Verify that the Flash plugin exists and that it can be enabled and disabled
1344 std::vector
<content::WebPluginInfo
> plugins
;
1345 GetPluginList(&plugins
);
1346 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1349 PluginPrefs
* plugin_prefs
=
1350 PluginPrefs::GetForProfile(browser()->profile()).get();
1351 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1353 // Disable all plugins.
1354 base::ListValue disabled_plugins
;
1355 disabled_plugins
.Append(new base::StringValue("*"));
1357 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1358 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1359 UpdateProviderPolicy(policies
);
1360 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1361 // The user shouldn't be able to enable it.
1362 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1363 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1365 // Now open an exception for flash.
1366 base::ListValue disabled_plugins_exceptions
;
1367 disabled_plugins_exceptions
.Append(new base::StringValue("*Flash*"));
1368 policies
.Set(key::kDisabledPluginsExceptions
, POLICY_LEVEL_MANDATORY
,
1369 POLICY_SCOPE_USER
, disabled_plugins_exceptions
.DeepCopy(), NULL
);
1370 UpdateProviderPolicy(policies
);
1371 // It should revert to the user's preference automatically.
1372 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1373 // And the user should be able to disable and enable again.
1374 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1375 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1376 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1377 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1380 IN_PROC_BROWSER_TEST_F(PolicyTest
, EnabledPlugins
) {
1381 // Verifies that a plugin can be force-installed with a policy.
1382 std::vector
<content::WebPluginInfo
> plugins
;
1383 GetPluginList(&plugins
);
1384 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1387 PluginPrefs
* plugin_prefs
=
1388 PluginPrefs::GetForProfile(browser()->profile()).get();
1389 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1391 // The user disables it and then a policy forces it to be enabled.
1392 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1393 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1394 base::ListValue plugin_list
;
1395 plugin_list
.Append(new base::StringValue(content::kFlashPluginName
));
1397 policies
.Set(key::kEnabledPlugins
, POLICY_LEVEL_MANDATORY
,
1398 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1399 UpdateProviderPolicy(policies
);
1400 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1401 // The user can't disable it anymore.
1402 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, false));
1403 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1405 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1406 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1407 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1408 UpdateProviderPolicy(policies
);
1409 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1412 IN_PROC_BROWSER_TEST_F(PolicyTest
, AlwaysAuthorizePlugins
) {
1413 // Verifies that dangerous plugins can be always authorized to run with
1416 // Verify that the test page exists. It is only present in checkouts with
1418 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1419 base::FilePath(FILE_PATH_LITERAL("plugin")),
1420 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1422 "Test skipped because plugin/quicktime.html test file wasn't found.";
1426 ServeContentTestData();
1427 // No plugins at startup.
1428 EXPECT_EQ(0, CountPlugins());
1430 content::WebContents
* contents
=
1431 browser()->tab_strip_model()->GetActiveWebContents();
1432 ASSERT_TRUE(contents
);
1433 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
1434 ASSERT_TRUE(infobar_service
);
1435 EXPECT_EQ(0u, infobar_service
->infobar_count());
1437 base::FilePath
path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1438 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1439 ui_test_utils::NavigateToURL(browser(), url
);
1440 // This should have triggered the dangerous plugin infobar.
1441 ASSERT_EQ(1u, infobar_service
->infobar_count());
1443 infobar_service
->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1444 // And the plugin isn't running.
1445 EXPECT_EQ(0, CountPlugins());
1447 // Now set a policy to always authorize this.
1449 policies
.Set(key::kAlwaysAuthorizePlugins
,
1450 POLICY_LEVEL_MANDATORY
,
1452 new base::FundamentalValue(true),
1454 UpdateProviderPolicy(policies
);
1455 // Reloading the page shouldn't trigger the infobar this time.
1456 ui_test_utils::NavigateToURL(browser(), url
);
1457 EXPECT_EQ(0u, infobar_service
->infobar_count());
1458 // And the plugin started automatically.
1459 EXPECT_EQ(1, CountPlugins());
1462 IN_PROC_BROWSER_TEST_F(PolicyTest
, DeveloperToolsDisabled
) {
1463 // Verifies that access to the developer tools can be disabled.
1466 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1467 content::WebContents
* contents
=
1468 browser()->tab_strip_model()->GetActiveWebContents();
1469 DevToolsWindow
* devtools_window
=
1470 DevToolsWindow::GetInstanceForInspectedWebContents(contents
);
1471 EXPECT_TRUE(devtools_window
);
1473 // Disable devtools via policy.
1475 policies
.Set(key::kDeveloperToolsDisabled
,
1476 POLICY_LEVEL_MANDATORY
,
1478 new base::FundamentalValue(true),
1480 content::WindowedNotificationObserver
close_observer(
1481 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
1482 content::Source
<content::WebContents
>(
1483 DevToolsWindowTesting::Get(devtools_window
)->main_web_contents()));
1484 UpdateProviderPolicy(policies
);
1485 // wait for devtools close
1486 close_observer
.Wait();
1487 // The existing devtools window should have closed.
1488 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1489 // And it's not possible to open it again.
1490 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1491 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1494 // TODO(samarth): remove along with rest of NTP4 code.
1495 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_WebStoreIconHidden
) {
1496 #if defined(OS_WIN) && defined(USE_ASH)
1497 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1498 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1499 switches::kAshBrowserTests
))
1503 // Verifies that the web store icons can be hidden from the new tab page.
1505 // Open new tab page and look for the web store icons.
1506 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1507 content::WebContents
* contents
=
1508 browser()->tab_strip_model()->GetActiveWebContents();
1510 #if !defined(OS_CHROMEOS)
1511 // Look for web store's app ID in the apps page.
1512 EXPECT_TRUE(ContainsVisibleElement(contents
,
1513 "ahfgeienlihckogmohjhadlkjgocpleb"));
1516 // The next NTP has no footer.
1517 if (ContainsVisibleElement(contents
, "footer"))
1518 EXPECT_TRUE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1520 // Turn off the web store icons.
1522 policies
.Set(key::kHideWebStoreIcon
,
1523 POLICY_LEVEL_MANDATORY
,
1525 new base::FundamentalValue(true),
1527 UpdateProviderPolicy(policies
);
1529 // The web store icons should now be hidden.
1530 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1531 EXPECT_FALSE(ContainsVisibleElement(contents
,
1532 "ahfgeienlihckogmohjhadlkjgocpleb"));
1533 EXPECT_FALSE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1536 IN_PROC_BROWSER_TEST_F(PolicyTest
, DownloadDirectory
) {
1537 // Verifies that the download directory can be forced by policy.
1539 // Set the initial download directory.
1540 base::ScopedTempDir initial_dir
;
1541 ASSERT_TRUE(initial_dir
.CreateUniqueTempDir());
1542 browser()->profile()->GetPrefs()->SetFilePath(
1543 prefs::kDownloadDefaultDirectory
, initial_dir
.path());
1544 // Don't prompt for the download location during this test.
1545 browser()->profile()->GetPrefs()->SetBoolean(
1546 prefs::kPromptForDownload
, false);
1548 // Verify that downloads end up on the default directory.
1549 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1550 DownloadAndVerifyFile(browser(), initial_dir
.path(), file
);
1551 base::DieFileDie(initial_dir
.path().Append(file
), false);
1553 // Override the download directory with the policy and verify a download.
1554 base::ScopedTempDir forced_dir
;
1555 ASSERT_TRUE(forced_dir
.CreateUniqueTempDir());
1557 policies
.Set(key::kDownloadDirectory
,
1558 POLICY_LEVEL_MANDATORY
,
1560 new base::StringValue(forced_dir
.path().value()),
1562 UpdateProviderPolicy(policies
);
1563 DownloadAndVerifyFile(browser(), forced_dir
.path(), file
);
1564 // Verify that the first download location wasn't affected.
1565 EXPECT_FALSE(base::PathExists(initial_dir
.path().Append(file
)));
1568 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSelective
) {
1569 // Verifies that blacklisted extensions can't be installed.
1570 ExtensionService
* service
= extension_service();
1571 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1572 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1573 base::ListValue blacklist
;
1574 blacklist
.Append(new base::StringValue(kGoodCrxId
));
1576 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1577 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1578 UpdateProviderPolicy(policies
);
1580 // "good.crx" is blacklisted.
1581 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1582 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1584 // "adblock.crx" is not.
1585 const extensions::Extension
* adblock
= InstallExtension(kAdBlockCrxName
);
1586 ASSERT_TRUE(adblock
);
1587 EXPECT_EQ(kAdBlockCrxId
, adblock
->id());
1589 service
->GetExtensionById(kAdBlockCrxId
, true));
1592 // Flaky on windows; http://crbug.com/307994.
1594 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1596 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1598 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallBlacklistWildcard
) {
1599 // Verify that a wildcard blacklist takes effect.
1600 EXPECT_TRUE(InstallExtension(kAdBlockCrxName
));
1601 ExtensionService
* service
= extension_service();
1602 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1603 ASSERT_TRUE(service
->GetExtensionById(kAdBlockCrxId
, true));
1604 base::ListValue blacklist
;
1605 blacklist
.Append(new base::StringValue("*"));
1607 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1608 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1609 UpdateProviderPolicy(policies
);
1611 // AdBlock was automatically removed.
1612 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1614 // And can't be installed again, nor can good.crx.
1615 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1616 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1617 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1618 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1621 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSharedModules
) {
1622 // Verifies that shared_modules are not affected by the blacklist.
1624 const char kImporterId
[] = "pchakhniekfaeoddkifplhnfbffomabh";
1625 const char kSharedModuleId
[] = "nfgclafboonjbiafbllihiailjlhelpm";
1627 // Make sure that "import" and "export" are available to these extension IDs
1628 // by mocking the release channel.
1629 extensions::ScopedCurrentChannel
channel(chrome::VersionInfo::CHANNEL_DEV
);
1631 // Verify that the extensions are not installed initially.
1632 ExtensionService
* service
= extension_service();
1633 ASSERT_FALSE(service
->GetExtensionById(kImporterId
, true));
1634 ASSERT_FALSE(service
->GetExtensionById(kSharedModuleId
, true));
1636 // Mock the webstore update URL. This is where the shared module extension
1637 // will be installed from.
1638 base::FilePath update_xml_path
= base::FilePath(kTestExtensionsDir
)
1639 .AppendASCII("policy_shared_module")
1640 .AppendASCII("update.xml");
1641 GURL
update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path
));
1642 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1643 switches::kAppsGalleryUpdateURL
, update_xml_url
.spec());
1644 ui_test_utils::NavigateToURL(browser(), update_xml_url
);
1646 // Blacklist "*" but force-install the importer extension. The shared module
1647 // should be automatically installed too.
1648 base::ListValue blacklist
;
1649 blacklist
.AppendString("*");
1650 base::ListValue forcelist
;
1651 forcelist
.AppendString(
1652 base::StringPrintf("%s;%s", kImporterId
, update_xml_url
.spec().c_str()));
1654 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1655 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1656 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1657 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1659 extensions::ExtensionRegistry
* registry
=
1660 extensions::ExtensionRegistry::Get(browser()->profile());
1661 extensions::TestExtensionRegistryObserver
observe_importer(
1662 registry
, kImporterId
);
1663 extensions::TestExtensionRegistryObserver
observe_shared_module(
1664 registry
, kSharedModuleId
);
1665 UpdateProviderPolicy(policies
);
1666 observe_importer
.WaitForExtensionLoaded();
1667 observe_shared_module
.WaitForExtensionLoaded();
1669 // Verify that both extensions got installed.
1670 const extensions::Extension
* importer
=
1671 service
->GetExtensionById(kImporterId
, true);
1672 ASSERT_TRUE(importer
);
1673 EXPECT_EQ(kImporterId
, importer
->id());
1674 const extensions::Extension
* shared_module
=
1675 service
->GetExtensionById(kSharedModuleId
, true);
1676 ASSERT_TRUE(shared_module
);
1677 EXPECT_EQ(kSharedModuleId
, shared_module
->id());
1678 EXPECT_TRUE(shared_module
->is_shared_module());
1680 // Verify the dependency.
1681 scoped_ptr
<extensions::ExtensionSet
> set
=
1682 service
->shared_module_service()->GetDependentExtensions(shared_module
);
1684 EXPECT_EQ(1u, set
->size());
1685 EXPECT_TRUE(set
->Contains(importer
->id()));
1687 std::vector
<extensions::SharedModuleInfo::ImportInfo
> imports
=
1688 extensions::SharedModuleInfo::GetImports(importer
);
1689 ASSERT_EQ(1u, imports
.size());
1690 EXPECT_EQ(kSharedModuleId
, imports
[0].extension_id
);
1693 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallWhitelist
) {
1694 // Verifies that the whitelist can open exceptions to the blacklist.
1695 ExtensionService
* service
= extension_service();
1696 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1697 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1698 base::ListValue blacklist
;
1699 blacklist
.Append(new base::StringValue("*"));
1700 base::ListValue whitelist
;
1701 whitelist
.Append(new base::StringValue(kGoodCrxId
));
1703 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1704 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1705 policies
.Set(key::kExtensionInstallWhitelist
, POLICY_LEVEL_MANDATORY
,
1706 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
1707 UpdateProviderPolicy(policies
);
1708 // "adblock.crx" is blacklisted.
1709 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1710 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1711 // "good.crx" has a whitelist exception.
1712 const extensions::Extension
* good
= InstallExtension(kGoodCrxName
);
1714 EXPECT_EQ(kGoodCrxId
, good
->id());
1715 EXPECT_EQ(good
, service
->GetExtensionById(kGoodCrxId
, true));
1716 // The user can also remove this extension.
1717 UninstallExtension(kGoodCrxId
, true);
1720 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallForcelist
) {
1721 // Verifies that extensions that are force-installed by policies are
1722 // installed and can't be uninstalled.
1723 ExtensionService
* service
= extension_service();
1724 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1726 // Extensions that are force-installed come from an update URL, which defaults
1727 // to the webstore. Use a mock URL for this test with an update manifest
1728 // that includes "good_v1.crx".
1729 base::FilePath path
=
1730 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1731 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1733 // Setting the forcelist extension should install "good_v1.crx".
1734 base::ListValue forcelist
;
1735 forcelist
.Append(new base::StringValue(
1736 base::StringPrintf("%s;%s", kGoodCrxId
, url
.spec().c_str())));
1738 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1739 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1740 content::WindowedNotificationObserver
observer(
1741 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1742 content::NotificationService::AllSources());
1743 UpdateProviderPolicy(policies
);
1745 // Note: Cannot check that the notification details match the expected
1746 // exception, since the details object has already been freed prior to
1747 // the completion of observer.Wait().
1749 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1751 // The user is not allowed to uninstall force-installed extensions.
1752 UninstallExtension(kGoodCrxId
, false);
1754 // The user is not allowed to load an unpacked extension with the
1755 // same ID as a force-installed extension.
1756 LoadUnpackedExtension(kGoodUnpackedExt
, false);
1758 // Loading other unpacked extensions are not blocked.
1759 LoadUnpackedExtension(kAppUnpackedExt
, true);
1761 const std::string old_version_number
=
1762 service
->GetExtensionById(kGoodCrxId
, true)->version()->GetString();
1764 base::FilePath test_path
;
1765 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
1767 TestRequestInterceptor
interceptor(
1769 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
1770 interceptor
.PushJobCallback(
1771 TestRequestInterceptor::FileJob(
1772 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
1774 // Updating the force-installed extension.
1775 extensions::ExtensionUpdater
* updater
= service
->updater();
1776 extensions::ExtensionUpdater::CheckParams params
;
1777 params
.install_immediately
= true;
1778 content::WindowedNotificationObserver
update_observer(
1779 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1780 content::NotificationService::AllSources());
1781 updater
->CheckNow(params
);
1782 update_observer
.Wait();
1784 const base::Version
* new_version
=
1785 service
->GetExtensionById(kGoodCrxId
, true)->version();
1786 ASSERT_TRUE(new_version
->IsValid());
1787 base::Version
old_version(old_version_number
);
1788 ASSERT_TRUE(old_version
.IsValid());
1790 EXPECT_EQ(1, new_version
->CompareTo(old_version
));
1792 EXPECT_EQ(0u, interceptor
.GetPendingSize());
1794 // Wait until any background pages belonging to force-installed extensions
1795 // have been loaded.
1796 extensions::ProcessManager
* manager
=
1797 extensions::ProcessManager::Get(browser()->profile());
1798 extensions::ProcessManager::ViewSet all_views
= manager
->GetAllViews();
1799 for (extensions::ProcessManager::ViewSet::const_iterator iter
=
1801 iter
!= all_views
.end();) {
1802 if (!(*iter
)->IsLoading()) {
1805 content::WebContents
* web_contents
=
1806 content::WebContents::FromRenderViewHost(*iter
);
1807 ASSERT_TRUE(web_contents
);
1808 WebContentsLoadedOrDestroyedWatcher(web_contents
).Wait();
1810 // Test activity may have modified the set of extension processes during
1811 // message processing, so re-start the iteration to catch added/removed
1813 all_views
= manager
->GetAllViews();
1814 iter
= all_views
.begin();
1818 // Test policy-installed extensions are reloaded when killed.
1819 BackgroundContentsService::
1820 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1821 content::WindowedNotificationObserver
extension_crashed_observer(
1822 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
1823 content::NotificationService::AllSources());
1824 content::WindowedNotificationObserver
extension_loaded_observer(
1825 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
1826 content::NotificationService::AllSources());
1827 extensions::ExtensionHost
* extension_host
=
1828 extensions::ProcessManager::Get(browser()->profile())
1829 ->GetBackgroundHostForExtension(kGoodCrxId
);
1830 extension_host
->render_process_host()->Shutdown(content::RESULT_CODE_KILLED
,
1832 extension_crashed_observer
.Wait();
1833 extension_loaded_observer
.Wait();
1836 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionRecommendedInstallationMode
) {
1837 // Verifies that extensions that are recommended-installed by policies are
1838 // installed, can be disabled but not uninstalled.
1839 ExtensionService
* service
= extension_service();
1840 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1842 base::FilePath path
=
1843 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1844 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1846 // Setting the forcelist extension should install "good_v1.crx".
1847 base::DictionaryValue dict_value
;
1848 dict_value
.SetString(std::string(kGoodCrxId
) + "." +
1849 extensions::schema_constants::kInstallationMode
,
1850 extensions::schema_constants::kNormalInstalled
);
1851 dict_value
.SetString(
1852 std::string(kGoodCrxId
) + "." + extensions::schema_constants::kUpdateUrl
,
1855 policies
.Set(key::kExtensionSettings
,
1856 POLICY_LEVEL_MANDATORY
,
1858 dict_value
.DeepCopy(),
1860 content::WindowedNotificationObserver
observer(
1861 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1862 content::NotificationService::AllSources());
1863 UpdateProviderPolicy(policies
);
1866 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1868 // The user is not allowed to uninstall recommended-installed extensions.
1869 UninstallExtension(kGoodCrxId
, false);
1871 // Explictly re-enables the extension.
1872 service
->EnableExtension(kGoodCrxId
);
1874 // But the user is allowed to disable them.
1875 EXPECT_TRUE(service
->IsExtensionEnabled(kGoodCrxId
));
1876 DisableExtension(kGoodCrxId
);
1877 EXPECT_FALSE(service
->IsExtensionEnabled(kGoodCrxId
));
1880 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionAllowedTypes
) {
1881 // Verifies that extensions are blocked if policy specifies an allowed types
1882 // list and the extension's type is not on that list.
1883 ExtensionService
* service
= extension_service();
1884 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1885 ASSERT_FALSE(service
->GetExtensionById(kHostedAppCrxId
, true));
1887 base::ListValue allowed_types
;
1888 allowed_types
.AppendString("hosted_app");
1890 policies
.Set(key::kExtensionAllowedTypes
, POLICY_LEVEL_MANDATORY
,
1891 POLICY_SCOPE_USER
, allowed_types
.DeepCopy(), NULL
);
1892 UpdateProviderPolicy(policies
);
1894 // "good.crx" is blocked.
1895 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1896 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1898 // "hosted_app.crx" is of a whitelisted type.
1899 const extensions::Extension
* hosted_app
= InstallExtension(kHostedAppCrxName
);
1900 ASSERT_TRUE(hosted_app
);
1901 EXPECT_EQ(kHostedAppCrxId
, hosted_app
->id());
1902 EXPECT_EQ(hosted_app
, service
->GetExtensionById(kHostedAppCrxId
, true));
1904 // The user can remove the extension.
1905 UninstallExtension(kHostedAppCrxId
, true);
1908 // Checks that a click on an extension CRX download triggers the extension
1909 // installation prompt without further user interaction when the source is
1910 // whitelisted by policy.
1911 // Flaky on windows; http://crbug.com/295729 .
1913 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1915 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1917 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallSources
) {
1918 ExtensionInstallPrompt::g_auto_confirm_for_tests
=
1919 ExtensionInstallPrompt::ACCEPT
;
1921 const GURL
install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1922 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1923 const GURL
referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1924 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1926 base::ScopedTempDir download_directory
;
1927 ASSERT_TRUE(download_directory
.CreateUniqueTempDir());
1928 DownloadPrefs
* download_prefs
=
1929 DownloadPrefs::FromBrowserContext(browser()->profile());
1930 download_prefs
->SetDownloadPath(download_directory
.path());
1932 const GURL
download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1933 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1934 ui_test_utils::NavigateToURL(browser(), download_page_url
);
1936 // As long as the policy is not present, extensions are considered dangerous.
1937 content::DownloadTestObserverTerminal
download_observer(
1938 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1939 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
);
1941 download_observer
.WaitForFinished();
1943 // Install the policy and trigger another download.
1944 base::ListValue install_sources
;
1945 install_sources
.AppendString(install_source_url
.spec());
1946 install_sources
.AppendString(referrer_url
.spec());
1948 policies
.Set(key::kExtensionInstallSources
, POLICY_LEVEL_MANDATORY
,
1949 POLICY_SCOPE_USER
, install_sources
.DeepCopy(), NULL
);
1950 UpdateProviderPolicy(policies
);
1952 content::WindowedNotificationObserver
observer(
1953 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1954 content::NotificationService::AllSources());
1957 // Note: Cannot check that the notification details match the expected
1958 // exception, since the details object has already been freed prior to
1959 // the completion of observer.Wait().
1961 // The first extension shouldn't be present, the second should be there.
1962 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId
, true));
1963 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId
, false));
1966 // Verifies that extensions with version older than the minimum version required
1967 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
1968 // policy changes as well as regular auto-updater scheduled updates.
1969 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequired
) {
1970 ExtensionService
* service
= extension_service();
1971 extensions::ExtensionRegistry
* registry
=
1972 extensions::ExtensionRegistry::Get(browser()->profile());
1973 extensions::ExtensionPrefs
* extension_prefs
=
1974 extensions::ExtensionPrefs::Get(browser()->profile());
1976 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
1977 service
->updater()->StopTimerForTesting();
1979 // Setup interceptor for extension updates.
1980 base::FilePath test_path
;
1981 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
1982 TestRequestInterceptor
interceptor(
1984 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
1985 interceptor
.PushJobCallback(TestRequestInterceptor::BadRequestJob());
1986 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
1987 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
1989 // Install the extension.
1990 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
1991 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
1993 // Update policy to set a minimum version of 1.0.0.0, the extension (with
1994 // version 1.0.0.0) should still be enabled.
1996 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
1997 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.0");
1999 base::RunLoop().RunUntilIdle();
2001 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2003 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2004 // version 1.0.0.0) should now be disabled.
2005 EXPECT_EQ(2u, interceptor
.GetPendingSize());
2006 base::RunLoop service_request_run_loop
;
2007 interceptor
.AddRequestServicedCallback(
2008 service_request_run_loop
.QuitClosure());
2010 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2011 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2013 service_request_run_loop
.Run();
2014 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2016 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2017 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2018 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2020 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2021 // via the update URL in the manifest of the older version.
2022 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2024 content::WindowedNotificationObserver
update_observer(
2025 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2026 content::NotificationService::AllSources());
2027 service
->updater()->CheckSoon();
2028 update_observer
.Wait();
2030 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2032 // The extension should be auto-updated to newer version and re-enabled.
2033 EXPECT_EQ("1.0.0.1",
2034 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2035 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2038 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2040 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequiredAlt
) {
2041 ExtensionService
* service
= extension_service();
2042 extensions::ExtensionRegistry
* registry
=
2043 extensions::ExtensionRegistry::Get(browser()->profile());
2044 extensions::ExtensionPrefs
* extension_prefs
=
2045 extensions::ExtensionPrefs::Get(browser()->profile());
2047 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2048 service
->updater()->StopTimerForTesting();
2050 // Setup interceptor for extension updates.
2051 base::FilePath test_path
;
2052 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2053 TestRequestInterceptor
interceptor(
2055 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2056 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2057 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2059 // Set the policy to require an even higher minimum version this time.
2061 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2062 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.2");
2064 base::RunLoop().RunUntilIdle();
2066 // Install the 1.0.0.0 version, it should be installed but disabled.
2067 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2068 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2069 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2070 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2071 EXPECT_EQ("1.0.0.0",
2072 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2074 // An extension management policy update should trigger an update as well.
2075 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2077 content::WindowedNotificationObserver
update_observer(
2078 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2079 content::NotificationService::AllSources());
2081 // Set a higher minimum version, just intend to trigger a policy update.
2082 extensions::ExtensionManagementPolicyUpdater
management_policy(
2084 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.3");
2086 base::RunLoop().RunUntilIdle();
2087 update_observer
.Wait();
2089 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2091 // It should be updated to 1.0.0.1 but remain disabled.
2092 EXPECT_EQ("1.0.0.1",
2093 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2094 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2095 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2096 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2098 // Remove the minimum version requirement. The extension should be re-enabled.
2100 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2101 management_policy
.UnsetMinimumVersionRequired(kGoodCrxId
);
2103 base::RunLoop().RunUntilIdle();
2105 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2106 EXPECT_FALSE(extension_prefs
->HasDisableReason(
2107 kGoodCrxId
, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
));
2110 // Verifies that a force-installed extension which does not meet a subsequently
2111 // set minimum version requirement is handled well.
2112 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionForceInstalled
) {
2113 extensions::ExtensionRegistry
* registry
=
2114 extensions::ExtensionRegistry::Get(browser()->profile());
2115 extensions::ExtensionPrefs
* extension_prefs
=
2116 extensions::ExtensionPrefs::Get(browser()->profile());
2118 // Prepare the update URL for force installing.
2119 const base::FilePath path
=
2120 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
2121 const GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
2123 // Set policy to force-install the extension, it should be installed and
2125 content::WindowedNotificationObserver
install_observer(
2126 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2127 content::NotificationService::AllSources());
2128 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2130 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2131 management_policy
.SetIndividualExtensionAutoInstalled(kGoodCrxId
,
2134 base::RunLoop().RunUntilIdle();
2135 install_observer
.Wait();
2137 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2139 // Set policy a minimum version of "1.0.0.1", the extension now should be
2142 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2143 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2145 base::RunLoop().RunUntilIdle();
2146 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2147 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2148 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2149 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2152 IN_PROC_BROWSER_TEST_F(PolicyTest
, HomepageLocation
) {
2153 #if defined(OS_WIN) && defined(USE_ASH)
2154 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2155 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2156 switches::kAshBrowserTests
))
2160 // Verifies that the homepage can be configured with policies.
2161 // Set a default, and check that the home button navigates there.
2162 browser()->profile()->GetPrefs()->SetString(
2163 prefs::kHomePage
, chrome::kChromeUIPolicyURL
);
2164 browser()->profile()->GetPrefs()->SetBoolean(
2165 prefs::kHomePageIsNewTabPage
, false);
2166 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
),
2167 browser()->profile()->GetHomePage());
2168 content::WebContents
* contents
=
2169 browser()->tab_strip_model()->GetActiveWebContents();
2170 EXPECT_EQ(GURL(url::kAboutBlankURL
), contents
->GetURL());
2171 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2172 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
), contents
->GetURL());
2174 // Now override with policy.
2176 policies
.Set(key::kHomepageLocation
,
2177 POLICY_LEVEL_MANDATORY
,
2179 new base::StringValue(chrome::kChromeUICreditsURL
),
2181 UpdateProviderPolicy(policies
);
2182 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2183 content::WaitForLoadStop(contents
);
2184 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL
), contents
->GetURL());
2186 policies
.Set(key::kHomepageIsNewTabPage
,
2187 POLICY_LEVEL_MANDATORY
,
2189 new base::FundamentalValue(true),
2191 UpdateProviderPolicy(policies
);
2192 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2193 content::WaitForLoadStop(contents
);
2194 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL
), contents
->GetURL());
2197 IN_PROC_BROWSER_TEST_F(PolicyTest
, IncognitoEnabled
) {
2198 // Verifies that incognito windows can't be opened when disabled by policy.
2200 const BrowserList
* active_browser_list
=
2201 BrowserList::GetInstance(chrome::GetActiveDesktop());
2203 // Disable incognito via policy and verify that incognito windows can't be
2205 EXPECT_EQ(1u, active_browser_list
->size());
2206 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2208 policies
.Set(key::kIncognitoEnabled
,
2209 POLICY_LEVEL_MANDATORY
,
2211 new base::FundamentalValue(false),
2213 UpdateProviderPolicy(policies
);
2214 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2215 EXPECT_EQ(1u, active_browser_list
->size());
2216 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2218 // Enable via policy and verify that incognito windows can be opened.
2219 policies
.Set(key::kIncognitoEnabled
,
2220 POLICY_LEVEL_MANDATORY
,
2222 new base::FundamentalValue(true),
2224 UpdateProviderPolicy(policies
);
2225 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2226 EXPECT_EQ(2u, active_browser_list
->size());
2227 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2230 IN_PROC_BROWSER_TEST_F(PolicyTest
, Javascript
) {
2231 // Verifies that Javascript can be disabled.
2232 content::WebContents
* contents
=
2233 browser()->tab_strip_model()->GetActiveWebContents();
2234 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2235 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2236 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2237 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2239 // Disable Javascript via policy.
2241 policies
.Set(key::kJavascriptEnabled
,
2242 POLICY_LEVEL_MANDATORY
,
2244 new base::FundamentalValue(false),
2246 UpdateProviderPolicy(policies
);
2248 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2249 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2250 // Developer tools still work when javascript is disabled.
2251 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2252 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2253 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2254 // Javascript is always enabled for the internal pages.
2255 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL
));
2256 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2258 // The javascript content setting policy overrides the javascript policy.
2259 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2260 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2261 policies
.Set(key::kDefaultJavaScriptSetting
,
2262 POLICY_LEVEL_MANDATORY
,
2264 new base::FundamentalValue(CONTENT_SETTING_ALLOW
),
2266 UpdateProviderPolicy(policies
);
2267 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2268 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2271 IN_PROC_BROWSER_TEST_F(PolicyTest
, NetworkPrediction
) {
2272 PrefService
* prefs
= browser()->profile()->GetPrefs();
2274 // Enabled by default.
2275 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2277 // Disable by old, deprecated policy.
2279 policies
.Set(key::kDnsPrefetchingEnabled
,
2280 POLICY_LEVEL_MANDATORY
,
2282 new base::FundamentalValue(false),
2284 UpdateProviderPolicy(policies
);
2286 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs
));
2288 // Enabled by new policy, this should override old one.
2290 key::kNetworkPredictionOptions
,
2291 POLICY_LEVEL_MANDATORY
,
2293 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS
),
2295 UpdateProviderPolicy(policies
);
2297 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2300 IN_PROC_BROWSER_TEST_F(PolicyTest
, SavingBrowserHistoryDisabled
) {
2301 // Verifies that browsing history is not saved.
2303 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2304 POLICY_LEVEL_MANDATORY
,
2306 new base::FundamentalValue(true),
2308 UpdateProviderPolicy(policies
);
2309 GURL url
= ui_test_utils::GetTestUrl(
2310 base::FilePath(base::FilePath::kCurrentDirectory
),
2311 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2312 ui_test_utils::NavigateToURL(browser(), url
);
2313 // Verify that the navigation wasn't saved in the history.
2314 ui_test_utils::HistoryEnumerator
enumerator1(browser()->profile());
2315 EXPECT_EQ(0u, enumerator1
.urls().size());
2317 // Now flip the policy and try again.
2318 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2319 POLICY_LEVEL_MANDATORY
,
2321 new base::FundamentalValue(false),
2323 UpdateProviderPolicy(policies
);
2324 ui_test_utils::NavigateToURL(browser(), url
);
2325 // Verify that the navigation was saved in the history.
2326 ui_test_utils::HistoryEnumerator
enumerator2(browser()->profile());
2327 ASSERT_EQ(1u, enumerator2
.urls().size());
2328 EXPECT_EQ(url
, enumerator2
.urls()[0]);
2331 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2332 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_TranslateEnabled
) {
2333 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2334 if (TranslateService::IsTranslateBubbleEnabled())
2337 scoped_ptr
<test::CldDataHarness
> cld_data_scope
=
2338 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2339 ASSERT_NO_FATAL_FAILURE(cld_data_scope
->Init());
2341 // Verifies that translate can be forced enabled or disabled by policy.
2343 // Get the InfoBarService, and verify that there are no infobars on startup.
2344 content::WebContents
* contents
=
2345 browser()->tab_strip_model()->GetActiveWebContents();
2346 ASSERT_TRUE(contents
);
2347 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
2348 ASSERT_TRUE(infobar_service
);
2349 EXPECT_EQ(0u, infobar_service
->infobar_count());
2351 // Force enable the translate feature.
2353 policies
.Set(key::kTranslateEnabled
,
2354 POLICY_LEVEL_MANDATORY
,
2356 new base::FundamentalValue(true),
2358 UpdateProviderPolicy(policies
);
2359 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2360 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2361 // TranslateManager observes. This allows checking that an infobar is NOT
2362 // shown below, without polling for infobars for some indeterminate amount
2364 GURL url
= ui_test_utils::GetTestUrl(
2366 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2367 content::WindowedNotificationObserver
language_observer1(
2368 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2369 content::NotificationService::AllSources());
2370 ui_test_utils::NavigateToURL(browser(), url
);
2371 language_observer1
.Wait();
2373 // Verify the translation detected for this tab.
2374 ChromeTranslateClient
* chrome_translate_client
=
2375 ChromeTranslateClient::FromWebContents(contents
);
2376 ASSERT_TRUE(chrome_translate_client
);
2377 translate::LanguageState
& language_state
=
2378 chrome_translate_client
->GetLanguageState();
2379 EXPECT_EQ("fr", language_state
.original_language());
2380 EXPECT_TRUE(language_state
.page_needs_translation());
2381 EXPECT_FALSE(language_state
.translation_pending());
2382 EXPECT_FALSE(language_state
.translation_declined());
2383 EXPECT_FALSE(language_state
.IsPageTranslated());
2385 // Verify that the translate infobar showed up.
2386 ASSERT_EQ(1u, infobar_service
->infobar_count());
2387 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2388 translate::TranslateInfoBarDelegate
* translate_infobar_delegate
=
2389 infobar
->delegate()->AsTranslateInfoBarDelegate();
2390 ASSERT_TRUE(translate_infobar_delegate
);
2391 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE
,
2392 translate_infobar_delegate
->translate_step());
2393 EXPECT_EQ("fr", translate_infobar_delegate
->original_language_code());
2395 // Now force disable translate.
2396 infobar_service
->RemoveInfoBar(infobar
);
2397 EXPECT_EQ(0u, infobar_service
->infobar_count());
2398 policies
.Set(key::kTranslateEnabled
,
2399 POLICY_LEVEL_MANDATORY
,
2401 new base::FundamentalValue(false),
2403 UpdateProviderPolicy(policies
);
2404 // Navigating to the same URL now doesn't trigger an infobar.
2405 content::WindowedNotificationObserver
language_observer2(
2406 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2407 content::NotificationService::AllSources());
2408 ui_test_utils::NavigateToURL(browser(), url
);
2409 language_observer2
.Wait();
2410 EXPECT_EQ(0u, infobar_service
->infobar_count());
2413 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklist
) {
2414 // Checks that URLs can be blacklisted, and that exceptions can be made to
2417 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2418 // as URLRequestMockHTTPJobs.
2419 const char* kURLS
[] = {
2420 "http://aaa.com/empty.html",
2421 "http://bbb.com/empty.html",
2422 "http://sub.bbb.com/empty.html",
2423 "http://bbb.com/policy/blank.html",
2427 BrowserThread::PostTaskAndReply(
2428 BrowserThread::IO
, FROM_HERE
,
2429 base::Bind(RedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2430 loop
.QuitClosure());
2434 // Verify that "bbb.com" opens before applying the blacklist.
2435 CheckCanOpenURL(browser(), kURLS
[1]);
2438 base::ListValue blacklist
;
2439 blacklist
.Append(new base::StringValue("bbb.com"));
2441 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2442 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2443 UpdateProviderPolicy(policies
);
2444 FlushBlacklistPolicy();
2445 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2446 CheckCanOpenURL(browser(), kURLS
[0]);
2447 for (size_t i
= 1; i
< arraysize(kURLS
); ++i
)
2448 CheckURLIsBlocked(browser(), kURLS
[i
]);
2450 // Whitelist some sites of bbb.com.
2451 base::ListValue whitelist
;
2452 whitelist
.Append(new base::StringValue("sub.bbb.com"));
2453 whitelist
.Append(new base::StringValue("bbb.com/policy"));
2454 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2455 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2456 UpdateProviderPolicy(policies
);
2457 FlushBlacklistPolicy();
2458 CheckURLIsBlocked(browser(), kURLS
[1]);
2459 CheckCanOpenURL(browser(), kURLS
[2]);
2460 CheckCanOpenURL(browser(), kURLS
[3]);
2464 BrowserThread::PostTaskAndReply(
2465 BrowserThread::IO
, FROM_HERE
,
2466 base::Bind(UndoRedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2467 loop
.QuitClosure());
2472 #if defined(OS_MACOSX)
2473 // http://crbug.com/339240
2474 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2476 #define MAYBE_FileURLBlacklist FileURLBlacklist
2478 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_FileURLBlacklist
) {
2479 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2480 // with URLblacklisting and URLwhitelisting.
2482 base::FilePath test_path
;
2483 PathService::Get(chrome::DIR_TEST_DATA
, &test_path
);
2484 const std::string base_path
= "file://" + test_path
.AsUTF8Unsafe() +"/";
2485 const std::string folder_path
= base_path
+ "apptest/";
2486 const std::string file_path1
= base_path
+ "title1.html";
2487 const std::string file_path2
= folder_path
+ "basic.html";
2489 CheckCanOpenURL(browser(), file_path1
.c_str());
2490 CheckCanOpenURL(browser(), file_path2
.c_str());
2492 // Set a blacklist for all the files.
2493 base::ListValue blacklist
;
2494 blacklist
.Append(new base::StringValue("file://*"));
2496 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2497 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2498 UpdateProviderPolicy(policies
);
2499 FlushBlacklistPolicy();
2501 CheckURLIsBlocked(browser(), file_path1
.c_str());
2502 CheckURLIsBlocked(browser(), file_path2
.c_str());
2504 // Replace the URLblacklist with disabling the file scheme.
2505 blacklist
.Remove(base::StringValue("file://*"), NULL
);
2506 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2507 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2508 UpdateProviderPolicy(policies
);
2509 FlushBlacklistPolicy();
2511 PrefService
* prefs
= browser()->profile()->GetPrefs();
2512 const base::ListValue
* list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2513 EXPECT_EQ(list_url
->Find(base::StringValue("file://*")),
2516 base::ListValue disabledscheme
;
2517 disabledscheme
.Append(new base::StringValue("file"));
2518 policies
.Set(key::kDisabledSchemes
, POLICY_LEVEL_MANDATORY
,
2519 POLICY_SCOPE_USER
, disabledscheme
.DeepCopy(), NULL
);
2520 UpdateProviderPolicy(policies
);
2521 FlushBlacklistPolicy();
2523 list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2524 EXPECT_NE(list_url
->Find(base::StringValue("file://*")),
2527 // Whitelist one folder and blacklist an another just inside.
2528 base::ListValue whitelist
;
2529 whitelist
.Append(new base::StringValue(base_path
));
2530 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2531 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2532 blacklist
.Append(new base::StringValue(folder_path
));
2533 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2534 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2535 UpdateProviderPolicy(policies
);
2536 FlushBlacklistPolicy();
2538 CheckCanOpenURL(browser(), file_path1
.c_str());
2539 CheckURLIsBlocked(browser(), file_path2
.c_str());
2542 static bool IsMinSSLVersionTLS12(Profile
* profile
) {
2543 scoped_refptr
<net::SSLConfigService
> config_service(
2544 profile
->GetSSLConfigService());
2545 net::SSLConfig config
;
2546 config_service
->GetSSLConfig(&config
);
2547 return config
.version_min
== net::SSL_PROTOCOL_VERSION_TLS1_2
;
2550 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionMin
) {
2551 PrefService
* prefs
= g_browser_process
->local_state();
2553 const std::string
new_value("tls1.2");
2554 const std::string
default_value(prefs
->GetString(prefs::kSSLVersionMin
));
2556 EXPECT_NE(default_value
, new_value
);
2557 EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2560 policies
.Set(key::kSSLVersionMin
,
2561 POLICY_LEVEL_MANDATORY
,
2563 new base::StringValue(new_value
),
2565 UpdateProviderPolicy(policies
);
2567 EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2570 static bool IsMinSSLFallbackVersionTLS12(Profile
* profile
) {
2571 scoped_refptr
<net::SSLConfigService
> config_service(
2572 profile
->GetSSLConfigService());
2573 net::SSLConfig config
;
2574 config_service
->GetSSLConfig(&config
);
2575 return config
.version_fallback_min
== net::SSL_PROTOCOL_VERSION_TLS1_2
;
2578 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionFallbackMin
) {
2579 PrefService
* prefs
= g_browser_process
->local_state();
2581 const std::string
new_value("tls1.2");
2582 const std::string
default_value(
2583 prefs
->GetString(prefs::kSSLVersionFallbackMin
));
2585 EXPECT_NE(default_value
, new_value
);
2586 EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2589 policies
.Set(key::kSSLVersionFallbackMin
,
2590 POLICY_LEVEL_MANDATORY
,
2592 new base::StringValue(new_value
),
2594 UpdateProviderPolicy(policies
);
2596 EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2599 #if !defined(OS_MACOSX)
2600 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedBrowser
) {
2602 policies
.Set(key::kFullscreenAllowed
,
2603 POLICY_LEVEL_MANDATORY
,
2605 new base::FundamentalValue(false),
2607 UpdateProviderPolicy(policies
);
2609 BrowserWindow
* browser_window
= browser()->window();
2610 ASSERT_TRUE(browser_window
);
2612 EXPECT_FALSE(browser_window
->IsFullscreen());
2613 chrome::ToggleFullscreenMode(browser());
2614 EXPECT_FALSE(browser_window
->IsFullscreen());
2617 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedApp
) {
2619 policies
.Set(key::kFullscreenAllowed
,
2620 POLICY_LEVEL_MANDATORY
,
2622 new base::FundamentalValue(false),
2624 UpdateProviderPolicy(policies
);
2626 const extensions::Extension
* extension
=
2627 LoadUnpackedExtension(kUnpackedFullscreenAppName
, true);
2628 ASSERT_TRUE(extension
);
2630 // Launch an app that tries to open a fullscreen window.
2631 TestAddAppWindowObserver
add_window_observer(
2632 extensions::AppWindowRegistry::Get(browser()->profile()));
2633 OpenApplication(AppLaunchParams(browser()->profile(), extension
,
2634 extensions::LAUNCH_CONTAINER_NONE
, NEW_WINDOW
,
2635 extensions::SOURCE_TEST
));
2636 extensions::AppWindow
* window
= add_window_observer
.WaitForAppWindow();
2637 ASSERT_TRUE(window
);
2639 // Verify that the window is not in fullscreen mode.
2640 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2642 // Verify that the window cannot be toggled into fullscreen mode via apps
2644 EXPECT_TRUE(content::ExecuteScript(
2645 window
->web_contents(),
2646 "chrome.app.window.current().fullscreen();"));
2647 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2649 // Verify that the window cannot be toggled into fullscreen mode from within
2650 // Chrome (e.g., using keyboard accelerators).
2651 window
->Fullscreen();
2652 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2656 #if defined(OS_CHROMEOS)
2657 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableScreenshotsFile
) {
2658 int screenshot_count
= CountScreenshots();
2660 // Make sure screenshots are counted correctly.
2661 TestScreenshotFile(true);
2662 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2664 // Check if trying to take a screenshot fails when disabled by policy.
2665 TestScreenshotFile(false);
2666 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2669 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableAudioOutput
) {
2670 // Set up the mock observer.
2671 chromeos::CrasAudioHandler
* audio_handler
= chromeos::CrasAudioHandler::Get();
2672 scoped_ptr
<TestAudioObserver
> test_observer(new TestAudioObserver
);
2673 audio_handler
->AddAudioObserver(test_observer
.get());
2675 bool prior_state
= audio_handler
->IsOutputMuted();
2676 // Make sure the audio is not muted and then toggle the policy and observe
2677 // if the output mute changed event is fired.
2678 audio_handler
->SetOutputMute(false);
2679 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2680 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2682 policies
.Set(key::kAudioOutputAllowed
,
2683 POLICY_LEVEL_MANDATORY
,
2685 new base::FundamentalValue(false),
2687 UpdateProviderPolicy(policies
);
2688 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2689 // This should not change the state now and should not trigger output mute
2691 audio_handler
->SetOutputMute(false);
2692 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2693 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2695 // Toggle back and observe if the output mute changed event is fired.
2696 policies
.Set(key::kAudioOutputAllowed
,
2697 POLICY_LEVEL_MANDATORY
,
2699 new base::FundamentalValue(true),
2701 UpdateProviderPolicy(policies
);
2702 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2703 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2704 audio_handler
->SetOutputMute(true);
2705 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2706 EXPECT_EQ(2, test_observer
->output_mute_changed_count());
2707 // Revert the prior state.
2708 audio_handler
->SetOutputMute(prior_state
);
2709 audio_handler
->RemoveAudioObserver(test_observer
.get());
2712 // Disabled, see http://crbug.com/315308.
2713 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_PRE_SessionLengthLimit
) {
2714 // Indicate that the session started 2 hours ago and no user activity has
2716 g_browser_process
->local_state()->SetInt64(
2717 prefs::kSessionStartTime
,
2718 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2719 .ToInternalValue());
2722 // Disabled, see http://crbug.com/315308.
2723 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_SessionLengthLimit
) {
2724 content::MockNotificationObserver observer
;
2725 content::NotificationRegistrar registrar
;
2726 registrar
.Add(&observer
,
2727 chrome::NOTIFICATION_APP_TERMINATING
,
2728 content::NotificationService::AllSources());
2730 // Set the session length limit to 3 hours. Verify that the session is not
2732 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2735 policies
.Set(key::kSessionLengthLimit
,
2736 POLICY_LEVEL_MANDATORY
,
2738 new base::FundamentalValue(kThreeHoursInMs
),
2740 UpdateProviderPolicy(policies
);
2741 base::RunLoop().RunUntilIdle();
2742 Mock::VerifyAndClearExpectations(&observer
);
2744 // Decrease the session length limit to 1 hour. Verify that the session is
2745 // terminated immediately.
2746 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2747 policies
.Set(key::kSessionLengthLimit
,
2748 POLICY_LEVEL_MANDATORY
,
2750 new base::FundamentalValue(kOneHourInMs
),
2752 UpdateProviderPolicy(policies
);
2753 base::RunLoop().RunUntilIdle();
2754 Mock::VerifyAndClearExpectations(&observer
);
2757 // Disabled, see http://crbug.com/315308.
2758 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2759 DISABLED_PRE_WaitForInitialUserActivityUsatisfied
) {
2760 // Indicate that the session started 2 hours ago and no user activity has
2762 g_browser_process
->local_state()->SetInt64(
2763 prefs::kSessionStartTime
,
2764 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2765 .ToInternalValue());
2768 // Disabled, see http://crbug.com/315308.
2769 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2770 DISABLED_WaitForInitialUserActivityUsatisfied
) {
2771 content::MockNotificationObserver observer
;
2772 content::NotificationRegistrar registrar
;
2773 registrar
.Add(&observer
,
2774 chrome::NOTIFICATION_APP_TERMINATING
,
2775 content::NotificationService::AllSources());
2777 // Require initial user activity.
2779 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2781 new base::FundamentalValue(true),
2783 UpdateProviderPolicy(policies
);
2784 base::RunLoop().RunUntilIdle();
2786 // Set the session length limit to 1 hour. Verify that the session is not
2788 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2790 policies
.Set(key::kSessionLengthLimit
,
2791 POLICY_LEVEL_MANDATORY
,
2793 new base::FundamentalValue(kOneHourInMs
),
2795 UpdateProviderPolicy(policies
);
2796 base::RunLoop().RunUntilIdle();
2797 Mock::VerifyAndClearExpectations(&observer
);
2800 // Disabled, see http://crbug.com/315308.
2801 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2802 DISABLED_PRE_WaitForInitialUserActivitySatisfied
) {
2803 // Indicate that initial user activity in this session occurred 2 hours ago.
2804 g_browser_process
->local_state()->SetInt64(
2805 prefs::kSessionStartTime
,
2806 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2807 .ToInternalValue());
2808 g_browser_process
->local_state()->SetBoolean(
2809 prefs::kSessionUserActivitySeen
,
2813 // Disabled, see http://crbug.com/315308.
2814 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2815 DISABLED_WaitForInitialUserActivitySatisfied
) {
2816 content::MockNotificationObserver observer
;
2817 content::NotificationRegistrar registrar
;
2818 registrar
.Add(&observer
,
2819 chrome::NOTIFICATION_APP_TERMINATING
,
2820 content::NotificationService::AllSources());
2822 // Require initial user activity and set the session length limit to 3 hours.
2823 // Verify that the session is not terminated.
2824 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2827 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2829 new base::FundamentalValue(true),
2831 policies
.Set(key::kSessionLengthLimit
,
2832 POLICY_LEVEL_MANDATORY
,
2834 new base::FundamentalValue(kThreeHoursInMs
),
2836 UpdateProviderPolicy(policies
);
2837 base::RunLoop().RunUntilIdle();
2838 Mock::VerifyAndClearExpectations(&observer
);
2840 // Decrease the session length limit to 1 hour. Verify that the session is
2841 // terminated immediately.
2842 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2843 policies
.Set(key::kSessionLengthLimit
,
2844 POLICY_LEVEL_MANDATORY
,
2846 new base::FundamentalValue(kOneHourInMs
),
2848 UpdateProviderPolicy(policies
);
2849 base::RunLoop().RunUntilIdle();
2850 Mock::VerifyAndClearExpectations(&observer
);
2853 IN_PROC_BROWSER_TEST_F(PolicyTest
, LargeCursorEnabled
) {
2854 // Verifies that the large cursor accessibility feature can be controlled
2856 chromeos::AccessibilityManager
* accessibility_manager
=
2857 chromeos::AccessibilityManager::Get();
2859 // Manually enable the large cursor.
2860 accessibility_manager
->EnableLargeCursor(true);
2861 EXPECT_TRUE(accessibility_manager
->IsLargeCursorEnabled());
2863 // Verify that policy overrides the manual setting.
2865 policies
.Set(key::kLargeCursorEnabled
,
2866 POLICY_LEVEL_MANDATORY
,
2868 new base::FundamentalValue(false),
2870 UpdateProviderPolicy(policies
);
2871 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2873 // Verify that the large cursor cannot be enabled manually anymore.
2874 accessibility_manager
->EnableLargeCursor(true);
2875 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2878 IN_PROC_BROWSER_TEST_F(PolicyTest
, SpokenFeedbackEnabled
) {
2879 // Verifies that the spoken feedback accessibility feature can be controlled
2881 chromeos::AccessibilityManager
* accessibility_manager
=
2882 chromeos::AccessibilityManager::Get();
2884 // Manually enable spoken feedback.
2885 accessibility_manager
->EnableSpokenFeedback(
2886 true, ui::A11Y_NOTIFICATION_NONE
);
2887 EXPECT_TRUE(accessibility_manager
->IsSpokenFeedbackEnabled());
2889 // Verify that policy overrides the manual setting.
2891 policies
.Set(key::kSpokenFeedbackEnabled
,
2892 POLICY_LEVEL_MANDATORY
,
2894 new base::FundamentalValue(false),
2896 UpdateProviderPolicy(policies
);
2897 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
2899 // Verify that spoken feedback cannot be enabled manually anymore.
2900 accessibility_manager
->EnableSpokenFeedback(
2901 true, ui::A11Y_NOTIFICATION_NONE
);
2902 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
2905 IN_PROC_BROWSER_TEST_F(PolicyTest
, HighContrastEnabled
) {
2906 // Verifies that the high contrast mode accessibility feature can be
2907 // controlled through policy.
2908 chromeos::AccessibilityManager
* accessibility_manager
=
2909 chromeos::AccessibilityManager::Get();
2911 // Manually enable high contrast mode.
2912 accessibility_manager
->EnableHighContrast(true);
2913 EXPECT_TRUE(accessibility_manager
->IsHighContrastEnabled());
2915 // Verify that policy overrides the manual setting.
2917 policies
.Set(key::kHighContrastEnabled
,
2918 POLICY_LEVEL_MANDATORY
,
2920 new base::FundamentalValue(false),
2922 UpdateProviderPolicy(policies
);
2923 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
2925 // Verify that high contrast mode cannot be enabled manually anymore.
2926 accessibility_manager
->EnableHighContrast(true);
2927 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
2930 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeNone
) {
2931 // Verifies that the screen magnifier can be disabled through policy.
2932 chromeos::MagnificationManager
* magnification_manager
=
2933 chromeos::MagnificationManager::Get();
2935 // Manually enable the full-screen magnifier.
2936 magnification_manager
->SetMagnifierType(ui::MAGNIFIER_FULL
);
2937 magnification_manager
->SetMagnifierEnabled(true);
2938 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
2939 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
2941 // Verify that policy overrides the manual setting.
2943 policies
.Set(key::kScreenMagnifierType
,
2944 POLICY_LEVEL_MANDATORY
,
2946 new base::FundamentalValue(0),
2948 UpdateProviderPolicy(policies
);
2949 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
2951 // Verify that the screen magnifier cannot be enabled manually anymore.
2952 magnification_manager
->SetMagnifierEnabled(true);
2953 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
2956 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeFull
) {
2957 // Verifies that the full-screen magnifier can be enabled through policy.
2958 chromeos::MagnificationManager
* magnification_manager
=
2959 chromeos::MagnificationManager::Get();
2961 // Verify that the screen magnifier is initially disabled.
2962 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
2964 // Verify that policy can enable the full-screen magnifier.
2966 policies
.Set(key::kScreenMagnifierType
,
2967 POLICY_LEVEL_MANDATORY
,
2969 new base::FundamentalValue(ui::MAGNIFIER_FULL
),
2971 UpdateProviderPolicy(policies
);
2972 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
2973 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
2975 // Verify that the screen magnifier cannot be disabled manually anymore.
2976 magnification_manager
->SetMagnifierEnabled(false);
2977 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
2980 IN_PROC_BROWSER_TEST_F(PolicyTest
, AccessibilityVirtualKeyboardEnabled
) {
2981 // Verifies that the on-screen keyboard accessibility feature can be
2982 // controlled through policy.
2983 chromeos::AccessibilityManager
* accessibility_manager
=
2984 chromeos::AccessibilityManager::Get();
2986 // Manually enable the on-screen keyboard.
2987 accessibility_manager
->EnableVirtualKeyboard(true);
2988 EXPECT_TRUE(accessibility_manager
->IsVirtualKeyboardEnabled());
2990 // Verify that policy overrides the manual setting.
2992 policies
.Set(key::kVirtualKeyboardEnabled
,
2993 POLICY_LEVEL_MANDATORY
,
2995 new base::FundamentalValue(false),
2997 UpdateProviderPolicy(policies
);
2998 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3000 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3001 accessibility_manager
->EnableVirtualKeyboard(true);
3002 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3005 IN_PROC_BROWSER_TEST_F(PolicyTest
, VirtualKeyboardEnabled
) {
3006 // Verify keyboard disabled by default.
3007 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3008 // Verify keyboard can be toggled by default.
3009 keyboard::SetTouchKeyboardEnabled(true);
3010 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3011 keyboard::SetTouchKeyboardEnabled(false);
3012 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3014 // Verify enabling the policy takes effect immediately and that that user
3015 // cannot disable the keyboard..
3017 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3018 POLICY_LEVEL_MANDATORY
,
3020 new base::FundamentalValue(true),
3022 UpdateProviderPolicy(policies
);
3023 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3024 keyboard::SetTouchKeyboardEnabled(false);
3025 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3027 // Verify that disabling the policy takes effect immediately and that the user
3028 // cannot enable the keyboard.
3029 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3030 POLICY_LEVEL_MANDATORY
,
3032 new base::FundamentalValue(false),
3034 UpdateProviderPolicy(policies
);
3035 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3036 keyboard::SetTouchKeyboardEnabled(true);
3037 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3044 static const char* kRestoredURLs
[] = {
3045 "http://aaa.com/empty.html",
3046 "http://bbb.com/empty.html",
3049 bool IsNonSwitchArgument(const base::CommandLine::StringType
& s
) {
3050 return s
.empty() || s
[0] != '-';
3055 // Similar to PolicyTest but allows setting policies before the browser is
3056 // created. Each test parameter is a method that sets up the early policies
3057 // and stores the expected startup URLs in |expected_urls_|.
3058 class RestoreOnStartupPolicyTest
3059 : public PolicyTest
,
3060 public testing::WithParamInterface
<
3061 void (RestoreOnStartupPolicyTest::*)(void)> {
3063 RestoreOnStartupPolicyTest() {}
3064 virtual ~RestoreOnStartupPolicyTest() {}
3066 #if defined(OS_CHROMEOS)
3067 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
3068 // TODO(nkostylev): Investigate if we can remove this switch.
3069 command_line
->AppendSwitch(switches::kCreateBrowserOnStartupForTests
);
3070 PolicyTest::SetUpCommandLine(command_line
);
3074 void SetUpInProcessBrowserTestFixture() override
{
3075 PolicyTest::SetUpInProcessBrowserTestFixture();
3076 // Set early policies now, before the browser is created.
3077 (this->*(GetParam()))();
3079 // Remove the non-switch arguments, so that session restore kicks in for
3081 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
3082 base::CommandLine::StringVector argv
= command_line
->argv();
3083 argv
.erase(std::remove_if(++argv
.begin(), argv
.end(), IsNonSwitchArgument
),
3085 command_line
->InitFromArgv(argv
);
3086 ASSERT_TRUE(std::equal(argv
.begin(), argv
.end(),
3087 command_line
->argv().begin()));
3090 void SetUpOnMainThread() override
{
3091 BrowserThread::PostTask(
3095 RedirectHostsToTestData
, kRestoredURLs
, arraysize(kRestoredURLs
)));
3098 void HomepageIsNotNTP() {
3099 // Verifies that policy can set the startup pages to the homepage, when
3100 // the homepage is not the NTP.
3103 key::kRestoreOnStartup
,
3104 POLICY_LEVEL_MANDATORY
,
3106 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3108 policies
.Set(key::kHomepageIsNewTabPage
,
3109 POLICY_LEVEL_MANDATORY
,
3111 new base::FundamentalValue(false),
3113 policies
.Set(key::kHomepageLocation
,
3114 POLICY_LEVEL_MANDATORY
,
3116 new base::StringValue(kRestoredURLs
[1]),
3118 provider_
.UpdateChromePolicy(policies
);
3120 expected_urls_
.push_back(GURL(kRestoredURLs
[1]));
3123 void HomepageIsNTP() {
3124 // Verifies that policy can set the startup pages to the homepage, when
3125 // the homepage is the NTP.
3128 key::kRestoreOnStartup
,
3129 POLICY_LEVEL_MANDATORY
,
3131 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3133 policies
.Set(key::kHomepageIsNewTabPage
,
3134 POLICY_LEVEL_MANDATORY
,
3136 new base::FundamentalValue(true),
3138 provider_
.UpdateChromePolicy(policies
);
3140 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3144 // Verifies that policy can set the startup pages to a list of URLs.
3145 base::ListValue urls
;
3146 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
) {
3147 urls
.Append(new base::StringValue(kRestoredURLs
[i
]));
3148 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3151 policies
.Set(key::kRestoreOnStartup
,
3152 POLICY_LEVEL_MANDATORY
,
3154 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs
),
3157 key::kRestoreOnStartupURLs
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3158 urls
.DeepCopy(), NULL
);
3159 provider_
.UpdateChromePolicy(policies
);
3163 // Verifies that policy can set the startup page to the NTP.
3166 key::kRestoreOnStartup
,
3167 POLICY_LEVEL_MANDATORY
,
3169 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab
),
3171 provider_
.UpdateChromePolicy(policies
);
3172 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3176 // Verifies that policy can set the startup pages to the last session.
3178 policies
.Set(key::kRestoreOnStartup
,
3179 POLICY_LEVEL_MANDATORY
,
3181 new base::FundamentalValue(SessionStartupPref::kPrefValueLast
),
3183 provider_
.UpdateChromePolicy(policies
);
3184 // This should restore the tabs opened at PRE_RunTest below.
3185 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
)
3186 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3189 std::vector
<GURL
> expected_urls_
;
3192 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, PRE_RunTest
) {
3193 // Open some tabs to verify if they are restored after the browser restarts.
3194 // Most policy settings override this, except kPrefValueLast which enforces
3196 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs
[0]));
3197 for (size_t i
= 1; i
< arraysize(kRestoredURLs
); ++i
) {
3198 content::WindowedNotificationObserver
observer(
3199 content::NOTIFICATION_LOAD_STOP
,
3200 content::NotificationService::AllSources());
3201 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs
[i
]),
3202 ui::PAGE_TRANSITION_LINK
);
3207 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, RunTest
) {
3208 #if defined(OS_WIN) && defined(USE_ASH)
3209 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3210 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3211 switches::kAshBrowserTests
))
3215 TabStripModel
* model
= browser()->tab_strip_model();
3216 int size
= static_cast<int>(expected_urls_
.size());
3217 EXPECT_EQ(size
, model
->count());
3218 for (int i
= 0; i
< size
&& i
< model
->count(); ++i
) {
3219 EXPECT_EQ(expected_urls_
[i
], model
->GetWebContentsAt(i
)->GetURL());
3223 INSTANTIATE_TEST_CASE_P(
3224 RestoreOnStartupPolicyTestInstance
,
3225 RestoreOnStartupPolicyTest
,
3226 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP
,
3227 &RestoreOnStartupPolicyTest::HomepageIsNTP
,
3228 &RestoreOnStartupPolicyTest::ListOfURLs
,
3229 &RestoreOnStartupPolicyTest::NTP
,
3230 &RestoreOnStartupPolicyTest::Last
));
3232 // Similar to PolicyTest but sets a couple of policies before the browser is
3234 class PolicyStatisticsCollectorTest
: public PolicyTest
{
3236 PolicyStatisticsCollectorTest() {}
3237 ~PolicyStatisticsCollectorTest() override
{}
3239 void SetUpInProcessBrowserTestFixture() override
{
3240 PolicyTest::SetUpInProcessBrowserTestFixture();
3242 policies
.Set(key::kShowHomeButton
,
3243 POLICY_LEVEL_MANDATORY
,
3245 new base::FundamentalValue(true),
3247 policies
.Set(key::kBookmarkBarEnabled
,
3248 POLICY_LEVEL_MANDATORY
,
3250 new base::FundamentalValue(false),
3252 policies
.Set(key::kHomepageLocation
,
3253 POLICY_LEVEL_MANDATORY
,
3255 new base::StringValue("http://chromium.org"),
3257 provider_
.UpdateChromePolicy(policies
);
3261 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest
, Startup
) {
3262 // Verifies that policy usage histograms are collected at startup.
3264 // BrowserPolicyConnector::Init() has already been called. Make sure the
3265 // CompleteInitialization() task has executed as well.
3266 content::RunAllPendingInMessageLoop();
3268 GURL kAboutHistograms
= GURL(std::string(url::kAboutScheme
) +
3269 std::string(url::kStandardSchemeSeparator
) +
3270 std::string(content::kChromeUIHistogramHost
));
3271 ui_test_utils::NavigateToURL(browser(), kAboutHistograms
);
3272 content::WebContents
* contents
=
3273 browser()->tab_strip_model()->GetActiveWebContents();
3275 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3277 "var nodes = document.querySelectorAll('body > pre');"
3279 "for (var i = 0; i < nodes.length; ++i) {"
3280 " var text = nodes[i].innerHTML;"
3281 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3286 "domAutomationController.send(result);",
3288 ASSERT_FALSE(text
.empty());
3289 const std::string kExpectedLabel
=
3290 "Histogram: Enterprise.Policies recorded 3 samples";
3291 EXPECT_EQ(kExpectedLabel
, text
.substr(0, kExpectedLabel
.size()));
3292 // HomepageLocation has policy ID 1.
3293 EXPECT_NE(std::string::npos
, text
.find("<br>1 ---"));
3294 // ShowHomeButton has policy ID 35.
3295 EXPECT_NE(std::string::npos
, text
.find("<br>35 ---"));
3296 // BookmarkBarEnabled has policy ID 82.
3297 EXPECT_NE(std::string::npos
, text
.find("<br>82 ---"));
3300 class MediaStreamDevicesControllerBrowserTest
3301 : public PolicyTest
,
3302 public testing::WithParamInterface
<bool> {
3304 MediaStreamDevicesControllerBrowserTest()
3305 : request_url_allowed_via_whitelist_(false) {
3306 policy_value_
= GetParam();
3308 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3310 // Configure a given policy map.
3311 // The |policy_name| is the name of either the audio or video capture allow
3312 // policy and must never be NULL.
3313 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3314 // policy is set. If non-NULL, the request_url_ will be set to be non empty
3315 // and the whitelist policy is set to contain either the |allow_rule| (if
3316 // non-NULL) or an "allow all" wildcard.
3317 void ConfigurePolicyMap(PolicyMap
* policies
, const char* policy_name
,
3318 const char* whitelist_policy
,
3319 const char* allow_rule
) {
3320 policies
->Set(policy_name
,
3321 POLICY_LEVEL_MANDATORY
,
3323 new base::FundamentalValue(policy_value_
),
3326 if (whitelist_policy
) {
3327 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3328 // in the media exceptions UI.
3329 // See discussion here: https://codereview.chromium.org/15738004/
3330 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3331 switches::kKioskMode
);
3333 // Add an entry to the whitelist that allows the specified URL regardless
3334 // of the setting of kAudioCapturedAllowed.
3335 request_url_
= GURL("http://www.example.com/foo");
3336 base::ListValue
* list
= new base::ListValue();
3338 list
->AppendString(allow_rule
);
3339 request_url_allowed_via_whitelist_
= true;
3341 list
->AppendString(ContentSettingsPattern::Wildcard().ToString());
3342 // We should ignore all wildcard entries in the whitelist, so even
3343 // though we've added an entry, it should be ignored and our expectation
3344 // is that the request has not been allowed via the whitelist.
3345 request_url_allowed_via_whitelist_
= false;
3347 policies
->Set(whitelist_policy
, POLICY_LEVEL_MANDATORY
,
3348 POLICY_SCOPE_USER
, list
, NULL
);
3352 void Accept(const content::MediaStreamDevices
& devices
,
3353 content::MediaStreamRequestResult result
,
3354 scoped_ptr
<content::MediaStreamUI
> ui
) {
3355 if (policy_value_
|| request_url_allowed_via_whitelist_
) {
3356 ASSERT_EQ(1U, devices
.size());
3357 ASSERT_EQ("fake_dev", devices
[0].id
);
3359 ASSERT_EQ(0U, devices
.size());
3363 void FinishAudioTest() {
3364 content::MediaStreamRequest
request(0, 0, 0,
3365 request_url_
.GetOrigin(), false,
3366 content::MEDIA_DEVICE_ACCESS
,
3367 std::string(), std::string(),
3368 content::MEDIA_DEVICE_AUDIO_CAPTURE
,
3369 content::MEDIA_NO_SERVICE
);
3370 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3371 // and microphone permissions at the same time.
3372 MediaStreamDevicesController
controller(
3373 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3374 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3375 controller
.Accept(false);
3377 base::MessageLoop::current()->QuitWhenIdle();
3380 void FinishVideoTest() {
3381 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3382 // and microphone permissions at the same time.
3383 content::MediaStreamRequest
request(0, 0, 0,
3384 request_url_
.GetOrigin(), false,
3385 content::MEDIA_DEVICE_ACCESS
,
3388 content::MEDIA_NO_SERVICE
,
3389 content::MEDIA_DEVICE_VIDEO_CAPTURE
);
3390 MediaStreamDevicesController
controller(
3391 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3392 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3393 controller
.Accept(false);
3395 base::MessageLoop::current()->QuitWhenIdle();
3399 bool request_url_allowed_via_whitelist_
;
3401 static const char kExampleRequestPattern
[];
3405 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern
[] =
3406 "http://[*.]example.com/";
3408 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3409 AudioCaptureAllowed
) {
3410 content::MediaStreamDevices audio_devices
;
3411 content::MediaStreamDevice
fake_audio_device(
3412 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3413 audio_devices
.push_back(fake_audio_device
);
3416 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
, NULL
, NULL
);
3417 UpdateProviderPolicy(policies
);
3419 content::BrowserThread::PostTaskAndReply(
3420 content::BrowserThread::IO
, FROM_HERE
,
3421 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3422 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3424 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3427 base::MessageLoop::current()->Run();
3430 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3431 AudioCaptureAllowedUrls
) {
3432 content::MediaStreamDevices audio_devices
;
3433 content::MediaStreamDevice
fake_audio_device(
3434 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3435 audio_devices
.push_back(fake_audio_device
);
3437 const char* allow_pattern
[] = {
3438 kExampleRequestPattern
,
3439 // This will set an allow-all policy whitelist. Since we do not allow
3440 // setting an allow-all entry in the whitelist, this entry should be ignored
3441 // and therefore the request should be denied.
3445 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3447 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
,
3448 key::kAudioCaptureAllowedUrls
, allow_pattern
[i
]);
3449 UpdateProviderPolicy(policies
);
3451 content::BrowserThread::PostTaskAndReply(
3452 content::BrowserThread::IO
, FROM_HERE
,
3454 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3455 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3458 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3461 base::MessageLoop::current()->Run();
3465 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3466 VideoCaptureAllowed
) {
3467 content::MediaStreamDevices video_devices
;
3468 content::MediaStreamDevice
fake_video_device(
3469 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3470 video_devices
.push_back(fake_video_device
);
3473 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
, NULL
, NULL
);
3474 UpdateProviderPolicy(policies
);
3476 content::BrowserThread::PostTaskAndReply(
3477 content::BrowserThread::IO
, FROM_HERE
,
3478 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3479 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3481 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3484 base::MessageLoop::current()->Run();
3487 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3488 VideoCaptureAllowedUrls
) {
3489 content::MediaStreamDevices video_devices
;
3490 content::MediaStreamDevice
fake_video_device(
3491 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3492 video_devices
.push_back(fake_video_device
);
3494 const char* allow_pattern
[] = {
3495 kExampleRequestPattern
,
3496 // This will set an allow-all policy whitelist. Since we do not allow
3497 // setting an allow-all entry in the whitelist, this entry should be ignored
3498 // and therefore the request should be denied.
3502 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3504 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
,
3505 key::kVideoCaptureAllowedUrls
, allow_pattern
[i
]);
3506 UpdateProviderPolicy(policies
);
3508 content::BrowserThread::PostTaskAndReply(
3509 content::BrowserThread::IO
, FROM_HERE
,
3510 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3511 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3514 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3517 base::MessageLoop::current()->Run();
3521 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance
,
3522 MediaStreamDevicesControllerBrowserTest
,
3525 #if !defined(OS_CHROMEOS)
3526 // Similar to PolicyTest but sets the proper policy before the browser is
3528 class PolicyVariationsServiceTest
: public PolicyTest
{
3530 void SetUpInProcessBrowserTestFixture() override
{
3531 PolicyTest::SetUpInProcessBrowserTestFixture();
3533 policies
.Set(key::kVariationsRestrictParameter
,
3534 POLICY_LEVEL_MANDATORY
,
3536 new base::StringValue("restricted"),
3538 provider_
.UpdateChromePolicy(policies
);
3542 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest
, VariationsURLIsValid
) {
3543 const std::string default_variations_url
=
3544 chrome_variations::VariationsService::
3545 GetDefaultVariationsServerURLForTesting();
3548 chrome_variations::VariationsService::GetVariationsServerURL(
3549 g_browser_process
->local_state(), std::string());
3550 EXPECT_TRUE(StartsWithASCII(url
.spec(), default_variations_url
, true));
3552 EXPECT_TRUE(net::GetValueForKeyInQuery(url
, "restrict", &value
));
3553 EXPECT_EQ("restricted", value
);
3556 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistSelective
) {
3557 base::ListValue blacklist
;
3558 blacklist
.Append(new base::StringValue("host.name"));
3560 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3561 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3562 UpdateProviderPolicy(policies
);
3564 PrefService
* prefs
= browser()->profile()->GetPrefs();
3565 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3566 prefs
, "host.name"));
3567 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3568 prefs
, "other.host.name"));
3571 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistWildcard
) {
3572 base::ListValue blacklist
;
3573 blacklist
.Append(new base::StringValue("*"));
3575 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3576 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3577 UpdateProviderPolicy(policies
);
3579 PrefService
* prefs
= browser()->profile()->GetPrefs();
3580 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3581 prefs
, "host.name"));
3582 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3583 prefs
, "other.host.name"));
3586 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingWhitelist
) {
3587 base::ListValue blacklist
;
3588 blacklist
.Append(new base::StringValue("*"));
3589 base::ListValue whitelist
;
3590 whitelist
.Append(new base::StringValue("host.name"));
3592 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3593 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3594 policies
.Set(key::kNativeMessagingWhitelist
, POLICY_LEVEL_MANDATORY
,
3595 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
3596 UpdateProviderPolicy(policies
);
3598 PrefService
* prefs
= browser()->profile()->GetPrefs();
3599 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3600 prefs
, "host.name"));
3601 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3602 prefs
, "other.host.name"));
3605 IN_PROC_BROWSER_TEST_F(PolicyTest
,
3606 EnableDeprecatedWebPlatformFeatures_ShowModalDialog
) {
3607 base::ListValue enabled_features
;
3608 enabled_features
.Append(new base::StringValue(
3609 "ShowModalDialog_EffectiveUntil20150430"));
3611 policies
.Set(key::kEnableDeprecatedWebPlatformFeatures
,
3612 POLICY_LEVEL_MANDATORY
,
3614 enabled_features
.DeepCopy(),
3616 UpdateProviderPolicy(policies
);
3618 // Policy only takes effect on new browsers, not existing browsers, so create
3620 Browser
* browser2
= CreateBrowser(browser()->profile());
3621 ui_test_utils::NavigateToURL(browser2
, GURL(url::kAboutBlankURL
));
3622 bool result
= false;
3623 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
3624 browser2
->tab_strip_model()->GetActiveWebContents(),
3625 "domAutomationController.send(window.showModalDialog !== undefined);",
3627 EXPECT_TRUE(result
);
3630 #endif // !defined(CHROME_OS)
3632 } // namespace policy