Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / policy / policy_browsertest.cc
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.
4
5 #include <algorithm>
6 #include <string>
7 #include <vector>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/files/file_enumerator.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/string_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_service.h"
41 #include "chrome/browser/extensions/shared_module_service.h"
42 #include "chrome/browser/extensions/unpacked_installer.h"
43 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
44 #include "chrome/browser/extensions/updater/extension_updater.h"
45 #include "chrome/browser/infobars/infobar_service.h"
46 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
47 #include "chrome/browser/media/media_stream_devices_controller.h"
48 #include "chrome/browser/metrics/variations/variations_service.h"
49 #include "chrome/browser/net/prediction_options.h"
50 #include "chrome/browser/net/ssl_config_service_manager.h"
51 #include "chrome/browser/net/url_request_mock_util.h"
52 #include "chrome/browser/plugins/plugin_prefs.h"
53 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
54 #include "chrome/browser/policy/profile_policy_connector.h"
55 #include "chrome/browser/policy/profile_policy_connector_factory.h"
56 #include "chrome/browser/prefs/session_startup_pref.h"
57 #include "chrome/browser/profiles/profile.h"
58 #include "chrome/browser/search/instant_service.h"
59 #include "chrome/browser/search/instant_service_factory.h"
60 #include "chrome/browser/search/search.h"
61 #include "chrome/browser/search_engines/template_url_service_factory.h"
62 #include "chrome/browser/translate/chrome_translate_client.h"
63 #include "chrome/browser/translate/cld_data_harness.h"
64 #include "chrome/browser/translate/translate_service.h"
65 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
66 #include "chrome/browser/ui/browser.h"
67 #include "chrome/browser/ui/browser_commands.h"
68 #include "chrome/browser/ui/browser_list.h"
69 #include "chrome/browser/ui/browser_tabstrip.h"
70 #include "chrome/browser/ui/browser_window.h"
71 #include "chrome/browser/ui/host_desktop.h"
72 #include "chrome/browser/ui/location_bar/location_bar.h"
73 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
74 #include "chrome/browser/ui/omnibox/omnibox_view.h"
75 #include "chrome/browser/ui/tabs/tab_strip_model.h"
76 #include "chrome/common/chrome_paths.h"
77 #include "chrome/common/chrome_switches.h"
78 #include "chrome/common/extensions/extension_constants.h"
79 #include "chrome/common/extensions/features/feature_channel.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/grit/generated_resources.h"
83 #include "chrome/test/base/in_process_browser_test.h"
84 #include "chrome/test/base/test_switches.h"
85 #include "chrome/test/base/ui_test_utils.h"
86 #include "components/content_settings/core/common/content_settings.h"
87 #include "components/content_settings/core/common/content_settings_pattern.h"
88 #include "components/infobars/core/infobar.h"
89 #include "components/policy/core/browser/browser_policy_connector.h"
90 #include "components/policy/core/common/external_data_fetcher.h"
91 #include "components/policy/core/common/mock_configuration_policy_provider.h"
92 #include "components/policy/core/common/policy_map.h"
93 #include "components/policy/core/common/policy_pref_names.h"
94 #include "components/policy/core/common/policy_service.h"
95 #include "components/policy/core/common/policy_service_impl.h"
96 #include "components/search_engines/template_url.h"
97 #include "components/search_engines/template_url_service.h"
98 #include "components/translate/core/browser/language_state.h"
99 #include "components/translate/core/browser/translate_infobar_delegate.h"
100 #include "content/public/browser/browser_child_process_host_iterator.h"
101 #include "content/public/browser/browser_context.h"
102 #include "content/public/browser/browser_thread.h"
103 #include "content/public/browser/child_process_data.h"
104 #include "content/public/browser/download_item.h"
105 #include "content/public/browser/download_manager.h"
106 #include "content/public/browser/gpu_data_manager.h"
107 #include "content/public/browser/notification_details.h"
108 #include "content/public/browser/notification_observer.h"
109 #include "content/public/browser/notification_registrar.h"
110 #include "content/public/browser/notification_service.h"
111 #include "content/public/browser/notification_source.h"
112 #include "content/public/browser/notification_types.h"
113 #include "content/public/browser/plugin_service.h"
114 #include "content/public/browser/render_process_host.h"
115 #include "content/public/browser/render_view_host.h"
116 #include "content/public/browser/web_contents.h"
117 #include "content/public/common/content_constants.h"
118 #include "content/public/common/content_paths.h"
119 #include "content/public/common/process_type.h"
120 #include "content/public/common/result_codes.h"
121 #include "content/public/common/url_constants.h"
122 #include "content/public/common/webplugininfo.h"
123 #include "content/public/test/browser_test_utils.h"
124 #include "content/public/test/download_test_observer.h"
125 #include "content/public/test/mock_notification_observer.h"
126 #include "content/public/test/test_navigation_observer.h"
127 #include "content/public/test/test_utils.h"
128 #include "extensions/browser/extension_host.h"
129 #include "extensions/browser/extension_registry.h"
130 #include "extensions/browser/extension_system.h"
131 #include "extensions/browser/process_manager.h"
132 #include "extensions/browser/test_extension_registry_observer.h"
133 #include "extensions/browser/uninstall_reason.h"
134 #include "extensions/common/constants.h"
135 #include "extensions/common/extension.h"
136 #include "extensions/common/extension_set.h"
137 #include "extensions/common/manifest_handlers/shared_module_info.h"
138 #include "net/base/net_errors.h"
139 #include "net/base/net_util.h"
140 #include "net/base/url_util.h"
141 #include "net/http/http_stream_factory.h"
142 #include "net/ssl/ssl_config.h"
143 #include "net/ssl/ssl_config_service.h"
144 #include "net/test/url_request/url_request_failed_job.h"
145 #include "net/test/url_request/url_request_mock_http_job.h"
146 #include "net/url_request/url_request.h"
147 #include "net/url_request/url_request_filter.h"
148 #include "policy/policy_constants.h"
149 #include "testing/gmock/include/gmock/gmock.h"
150 #include "testing/gtest/include/gtest/gtest.h"
151 #include "third_party/WebKit/public/web/WebInputEvent.h"
152 #include "ui/base/l10n/l10n_util.h"
153 #include "ui/base/page_transition_types.h"
154 #include "ui/base/resource/resource_bundle.h"
155 #include "url/gurl.h"
156
157 #if defined(OS_CHROMEOS)
158 #include "ash/accelerators/accelerator_controller.h"
159 #include "ash/accelerators/accelerator_table.h"
160 #include "ash/shell.h"
161 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
162 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
163 #include "chrome/browser/profiles/profile_manager.h"
164 #include "chrome/browser/ui/ash/screenshot_taker.h"
165 #include "chromeos/audio/cras_audio_handler.h"
166 #include "ui/chromeos/accessibility_types.h"
167 #include "ui/keyboard/keyboard_util.h"
168 #endif
169
170 #if !defined(OS_MACOSX)
171 #include "base/basictypes.h"
172 #include "base/compiler_specific.h"
173 #include "chrome/browser/ui/extensions/application_launch.h"
174 #include "extensions/browser/app_window/app_window.h"
175 #include "extensions/browser/app_window/app_window_registry.h"
176 #include "extensions/browser/app_window/native_app_window.h"
177 #include "ui/base/window_open_disposition.h"
178 #endif
179
180 using content::BrowserThread;
181 using net::URLRequestMockHTTPJob;
182 using testing::Mock;
183 using testing::Return;
184 using testing::_;
185
186 namespace policy {
187
188 namespace {
189
190 #if defined(OS_CHROMEOS)
191 const int kOneHourInMs = 60 * 60 * 1000;
192 const int kThreeHoursInMs = 180 * 60 * 1000;
193 #endif
194
195 const char kURL[] = "http://example.com";
196 const char kCookieValue[] = "converted=true";
197 // Assigned to Philip J. Fry to fix eventually.
198 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
199
200 const base::FilePath::CharType kTestExtensionsDir[] =
201     FILE_PATH_LITERAL("extensions");
202 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
203 const base::FilePath::CharType kAdBlockCrxName[] =
204     FILE_PATH_LITERAL("adblock.crx");
205 const base::FilePath::CharType kHostedAppCrxName[] =
206     FILE_PATH_LITERAL("hosted_app.crx");
207
208 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
209 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
210 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
211
212 const base::FilePath::CharType kGood2CrxManifestName[] =
213     FILE_PATH_LITERAL("good2_update_manifest.xml");
214 const base::FilePath::CharType kGoodV1CrxManifestName[] =
215     FILE_PATH_LITERAL("good_v1_update_manifest.xml");
216 const base::FilePath::CharType kGoodUnpackedExt[] =
217     FILE_PATH_LITERAL("good_unpacked");
218 const base::FilePath::CharType kAppUnpackedExt[] =
219     FILE_PATH_LITERAL("app");
220
221 #if !defined(OS_MACOSX)
222 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
223     FILE_PATH_LITERAL("fullscreen_app");
224 #endif  // !defined(OS_MACOSX)
225
226 // Filters requests to the hosts in |urls| and redirects them to the test data
227 // dir through URLRequestMockHTTPJobs.
228 void RedirectHostsToTestData(const char* const urls[], size_t size) {
229   // Map the given hosts to the test data dir.
230   net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
231   base::FilePath base_path;
232   PathService::Get(chrome::DIR_TEST_DATA, &base_path);
233   for (size_t i = 0; i < size; ++i) {
234     const GURL url(urls[i]);
235     EXPECT_TRUE(url.is_valid());
236     filter->AddUrlInterceptor(url,
237                               URLRequestMockHTTPJob::CreateInterceptor(
238                                   base_path, BrowserThread::GetBlockingPool()));
239   }
240 }
241
242 // Remove filters for requests to the hosts in |urls|.
243 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
244   // Map the given hosts to the test data dir.
245   net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
246   for (size_t i = 0; i < size; ++i) {
247     const GURL url(urls[i]);
248     EXPECT_TRUE(url.is_valid());
249     filter->RemoveUrlHandler(url);
250   }
251 }
252
253 // Fails requests using ERR_CONNECTION_RESET.
254 net::URLRequestJob* FailedJobFactory(
255     net::URLRequest* request,
256     net::NetworkDelegate* network_delegate,
257     const std::string& scheme) {
258   return new net::URLRequestFailedJob(
259       request, network_delegate, net::ERR_CONNECTION_RESET);
260 }
261
262 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
263 class MakeRequestFail {
264  public:
265   // Sets up the filter on IO thread such that requests to |host| fail.
266   explicit MakeRequestFail(const std::string& host) : host_(host) {
267     BrowserThread::PostTaskAndReply(
268         BrowserThread::IO, FROM_HERE,
269         base::Bind(MakeRequestFailOnIO, host_),
270         base::MessageLoop::QuitClosure());
271     content::RunMessageLoop();
272   }
273   ~MakeRequestFail() {
274     BrowserThread::PostTaskAndReply(
275         BrowserThread::IO, FROM_HERE,
276         base::Bind(UndoMakeRequestFailOnIO, host_),
277         base::MessageLoop::QuitClosure());
278     content::RunMessageLoop();
279   }
280
281  private:
282   // Filters requests to the |host| such that they fail. Run on IO thread.
283   static void MakeRequestFailOnIO(const std::string& host) {
284     net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
285     filter->AddHostnameHandler("http", host, &FailedJobFactory);
286     filter->AddHostnameHandler("https", host, &FailedJobFactory);
287   }
288
289   // Remove filters for requests to the |host|. Run on IO thread.
290   static void UndoMakeRequestFailOnIO(const std::string& host) {
291     net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
292     filter->RemoveHostnameHandler("http", host);
293     filter->RemoveHostnameHandler("https", host);
294   }
295
296   const std::string host_;
297 };
298
299 // Verifies that the given url |spec| can be opened. This assumes that |spec|
300 // points at empty.html in the test data dir.
301 void CheckCanOpenURL(Browser* browser, const char* spec) {
302   GURL url(spec);
303   ui_test_utils::NavigateToURL(browser, url);
304   content::WebContents* contents =
305       browser->tab_strip_model()->GetActiveWebContents();
306   EXPECT_EQ(url, contents->GetURL());
307   base::string16 spec16 = base::UTF8ToUTF16(url.spec());
308   base::string16 title =
309       l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
310   EXPECT_NE(title, contents->GetTitle());
311 }
312
313 // Verifies that access to the given url |spec| is blocked.
314 void CheckURLIsBlocked(Browser* browser, const char* spec) {
315   GURL url(spec);
316   ui_test_utils::NavigateToURL(browser, url);
317   content::WebContents* contents =
318       browser->tab_strip_model()->GetActiveWebContents();
319   EXPECT_EQ(url, contents->GetURL());
320   base::string16 spec16 = base::UTF8ToUTF16(url.spec());
321   base::string16 title =
322       l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
323   EXPECT_EQ(title, contents->GetTitle());
324
325   // Verify that the expected error page is being displayed.
326   bool result = false;
327   EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
328       contents,
329       "var textContent = document.body.textContent;"
330       "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
331       "domAutomationController.send(hasError);",
332       &result));
333   EXPECT_TRUE(result);
334 }
335
336 // Downloads a file named |file| and expects it to be saved to |dir|, which
337 // must be empty.
338 void DownloadAndVerifyFile(
339     Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
340   content::DownloadManager* download_manager =
341       content::BrowserContext::GetDownloadManager(browser->profile());
342   content::DownloadTestObserverTerminal observer(
343       download_manager, 1,
344       content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
345   GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
346   base::FilePath downloaded = dir.Append(file);
347   EXPECT_FALSE(base::PathExists(downloaded));
348   ui_test_utils::NavigateToURLWithDisposition(
349       browser, url, CURRENT_TAB,
350       ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
351   observer.WaitForFinished();
352   EXPECT_EQ(
353       1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
354   EXPECT_TRUE(base::PathExists(downloaded));
355   base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
356   EXPECT_EQ(file, enumerator.Next().BaseName());
357   EXPECT_EQ(base::FilePath(), enumerator.Next());
358 }
359
360 #if defined(OS_CHROMEOS)
361 int CountScreenshots() {
362   DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
363       ProfileManager::GetActiveUserProfile());
364   base::FileEnumerator enumerator(download_prefs->DownloadPath(),
365                                   false, base::FileEnumerator::FILES,
366                                   "Screenshot*");
367   int count = 0;
368   while (!enumerator.Next().empty())
369     count++;
370   return count;
371 }
372 #endif
373
374 // Checks if WebGL is enabled in the given WebContents.
375 bool IsWebGLEnabled(content::WebContents* contents) {
376   bool result = false;
377   EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
378       contents,
379       "var canvas = document.createElement('canvas');"
380       "var context = canvas.getContext('webgl');"
381       "domAutomationController.send(context != null);",
382       &result));
383   return result;
384 }
385
386 bool IsJavascriptEnabled(content::WebContents* contents) {
387   scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
388       contents->GetMainFrame(), "123");
389   int result = 0;
390   if (!value->GetAsInteger(&result))
391     EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
392   return result == 123;
393 }
394
395 bool IsNetworkPredictionEnabled(PrefService* prefs) {
396   return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs);
397 }
398
399 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
400                            const std::vector<content::WebPluginInfo>& in) {
401   *out = in;
402   base::MessageLoop::current()->QuitWhenIdle();
403 }
404
405 template<typename T>
406 void CopyValueAndQuit(T* out, T in) {
407   *out = in;
408   base::MessageLoop::current()->QuitWhenIdle();
409 }
410
411 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
412   content::PluginService* service = content::PluginService::GetInstance();
413   service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
414   content::RunMessageLoop();
415 }
416
417 const content::WebPluginInfo* GetFlashPlugin(
418     const std::vector<content::WebPluginInfo>& plugins) {
419   const content::WebPluginInfo* flash = NULL;
420   for (size_t i = 0; i < plugins.size(); ++i) {
421     if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
422       flash = &plugins[i];
423       break;
424     }
425   }
426 #if defined(OFFICIAL_BUILD)
427   // Official builds bundle Flash.
428   EXPECT_TRUE(flash);
429 #else
430   if (!flash)
431     LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
432 #endif
433   return flash;
434 }
435
436 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
437                       const content::WebPluginInfo* plugin,
438                       bool enabled) {
439   bool ok = false;
440   plugin_prefs->EnablePlugin(enabled, plugin->path,
441                              base::Bind(CopyValueAndQuit<bool>, &ok));
442   content::RunMessageLoop();
443   return ok;
444 }
445
446 int CountPluginsOnIOThread() {
447   int count = 0;
448   for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
449     if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
450         iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
451       count++;
452     }
453   }
454   return count;
455 }
456
457 int CountPlugins() {
458   int count = -1;
459   BrowserThread::PostTaskAndReplyWithResult(
460       BrowserThread::IO, FROM_HERE,
461       base::Bind(CountPluginsOnIOThread),
462       base::Bind(CopyValueAndQuit<int>, &count));
463   content::RunMessageLoop();
464   EXPECT_GE(count, 0);
465   return count;
466 }
467
468 void FlushBlacklistPolicy() {
469   // Updates of the URLBlacklist are done on IO, after building the blacklist
470   // on the blocking pool, which is initiated from IO.
471   content::RunAllPendingInMessageLoop(BrowserThread::IO);
472   BrowserThread::GetBlockingPool()->FlushForTesting();
473   content::RunAllPendingInMessageLoop(BrowserThread::IO);
474 }
475
476 bool ContainsVisibleElement(content::WebContents* contents,
477                             const std::string& id) {
478   bool result;
479   EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
480       contents,
481       "var elem = document.getElementById('" + id + "');"
482       "domAutomationController.send(!!elem && !elem.hidden);",
483       &result));
484   return result;
485 }
486
487 #if defined(OS_CHROMEOS)
488 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
489  public:
490   TestAudioObserver() : output_mute_changed_count_(0) {
491   }
492
493   int output_mute_changed_count() const {
494     return output_mute_changed_count_;
495   }
496
497   virtual ~TestAudioObserver() {}
498
499  protected:
500   // chromeos::CrasAudioHandler::AudioObserver overrides.
501   virtual void OnOutputMuteChanged() override {
502     ++output_mute_changed_count_;
503   }
504
505  private:
506   int output_mute_changed_count_;
507
508   DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
509 };
510 #endif
511
512 // This class waits until either a load stops or the WebContents is destroyed.
513 class WebContentsLoadedOrDestroyedWatcher
514     : public content::WebContentsObserver {
515  public:
516   explicit WebContentsLoadedOrDestroyedWatcher(
517       content::WebContents* web_contents);
518   ~WebContentsLoadedOrDestroyedWatcher() override;
519
520   // Waits until the WebContents's load is done or until it is destroyed.
521   void Wait();
522
523   // Overridden WebContentsObserver methods.
524   void WebContentsDestroyed() override;
525   void DidStopLoading(content::RenderViewHost* render_view_host) override;
526
527  private:
528   scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
529
530   DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
531 };
532
533 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
534     content::WebContents* web_contents)
535     : content::WebContentsObserver(web_contents),
536       message_loop_runner_(new content::MessageLoopRunner) {
537 }
538
539 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
540
541 void WebContentsLoadedOrDestroyedWatcher::Wait() {
542   message_loop_runner_->Run();
543 }
544
545 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
546   message_loop_runner_->Quit();
547 }
548
549 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
550     content::RenderViewHost* render_view_host) {
551   message_loop_runner_->Quit();
552 }
553
554 #if !defined(OS_MACOSX)
555
556 // Observer used to wait for the creation of a new app window.
557 class TestAddAppWindowObserver
558     : public extensions::AppWindowRegistry::Observer {
559  public:
560   explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
561   ~TestAddAppWindowObserver() override;
562
563   // extensions::AppWindowRegistry::Observer:
564   void OnAppWindowAdded(extensions::AppWindow* app_window) override;
565
566   extensions::AppWindow* WaitForAppWindow();
567
568  private:
569   extensions::AppWindowRegistry* registry_;  // Not owned.
570   extensions::AppWindow* window_;            // Not owned.
571   base::RunLoop run_loop_;
572
573   DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
574 };
575
576 TestAddAppWindowObserver::TestAddAppWindowObserver(
577     extensions::AppWindowRegistry* registry)
578     : registry_(registry), window_(NULL) {
579   registry_->AddObserver(this);
580 }
581
582 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
583   registry_->RemoveObserver(this);
584 }
585
586 void TestAddAppWindowObserver::OnAppWindowAdded(
587     extensions::AppWindow* app_window) {
588   window_ = app_window;
589   run_loop_.Quit();
590 }
591
592 extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
593   run_loop_.Run();
594   return window_;
595 }
596
597 #endif
598
599 }  // namespace
600
601 class PolicyTest : public InProcessBrowserTest {
602  protected:
603   PolicyTest() {}
604   ~PolicyTest() override {}
605
606   void SetUp() override {
607     test_extension_cache_.reset(new extensions::ExtensionCacheFake());
608     InProcessBrowserTest::SetUp();
609   }
610
611   void SetUpInProcessBrowserTestFixture() override {
612     CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
613     EXPECT_CALL(provider_, IsInitializationComplete(_))
614         .WillRepeatedly(Return(true));
615     BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
616   }
617
618   void SetUpOnMainThread() override {
619     BrowserThread::PostTask(
620         BrowserThread::IO, FROM_HERE,
621         base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
622     if (extension_service()->updater()) {
623       extension_service()->updater()->SetExtensionCacheForTesting(
624           test_extension_cache_.get());
625     }
626   }
627
628   // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
629   // instead of chrome::DIR_TEST_DATA.
630   void ServeContentTestData() {
631     base::FilePath root_http;
632     PathService::Get(content::DIR_TEST_DATA, &root_http);
633     BrowserThread::PostTaskAndReply(
634         BrowserThread::IO,
635         FROM_HERE,
636         base::Bind(URLRequestMockHTTPJob::AddUrlHandler,
637                    root_http,
638                    make_scoped_refptr(BrowserThread::GetBlockingPool())),
639         base::MessageLoop::current()->QuitWhenIdleClosure());
640     content::RunMessageLoop();
641   }
642
643   void SetScreenshotPolicy(bool enabled) {
644     PolicyMap policies;
645     policies.Set(key::kDisableScreenshots,
646                  POLICY_LEVEL_MANDATORY,
647                  POLICY_SCOPE_USER,
648                  new base::FundamentalValue(!enabled),
649                  NULL);
650     UpdateProviderPolicy(policies);
651   }
652
653 #if defined(OS_CHROMEOS)
654   class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
655    public:
656     virtual void OnScreenshotCompleted(
657         ScreenshotTakerObserver::Result screenshot_result,
658         const base::FilePath& screenshot_path) override {
659       BrowserThread::PostTaskAndReply(BrowserThread::IO,
660                                       FROM_HERE,
661                                       base::Bind(base::DoNothing),
662                                       base::MessageLoop::QuitClosure());
663     }
664
665     virtual ~QuitMessageLoopAfterScreenshot() {}
666   };
667
668   void TestScreenshotFile(bool enabled) {
669     // AddObserver is an ash-specific method, so just replace the screenshot
670     // taker with one we've created here.
671     scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
672     // ScreenshotTaker doesn't own this observer, so the observer's lifetime
673     // is tied to the test instead.
674     screenshot_taker->AddObserver(&observer_);
675     ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
676         screenshot_taker.Pass());
677
678     SetScreenshotPolicy(enabled);
679     ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
680         ash::TAKE_SCREENSHOT, ui::Accelerator());
681
682     content::RunMessageLoop();
683   }
684 #endif
685
686   ExtensionService* extension_service() {
687     extensions::ExtensionSystem* system =
688         extensions::ExtensionSystem::Get(browser()->profile());
689     return system->extension_service();
690   }
691
692   const extensions::Extension* InstallExtension(
693       const base::FilePath::StringType& name) {
694     base::FilePath extension_path(ui_test_utils::GetTestFilePath(
695         base::FilePath(kTestExtensionsDir), base::FilePath(name)));
696     scoped_refptr<extensions::CrxInstaller> installer =
697         extensions::CrxInstaller::CreateSilent(extension_service());
698     installer->set_allow_silent_install(true);
699     installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
700     installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
701
702     content::WindowedNotificationObserver observer(
703         extensions::NOTIFICATION_CRX_INSTALLER_DONE,
704         content::NotificationService::AllSources());
705     installer->InstallCrx(extension_path);
706     observer.Wait();
707     content::Details<const extensions::Extension> details = observer.details();
708     return details.ptr();
709   }
710
711   const extensions::Extension* LoadUnpackedExtension(
712       const base::FilePath::StringType& name, bool expect_success) {
713     base::FilePath extension_path(ui_test_utils::GetTestFilePath(
714         base::FilePath(kTestExtensionsDir), base::FilePath(name)));
715     scoped_refptr<extensions::UnpackedInstaller> installer =
716         extensions::UnpackedInstaller::Create(extension_service());
717     content::WindowedNotificationObserver observer(
718         expect_success ? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
719                        : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
720         content::NotificationService::AllSources());
721     installer->Load(extension_path);
722     observer.Wait();
723
724     const extensions::ExtensionSet* extensions =
725         extension_service()->extensions();
726     for (extensions::ExtensionSet::const_iterator it = extensions->begin();
727          it != extensions->end(); ++it) {
728       if ((*it)->path() == extension_path)
729         return it->get();
730     }
731     return NULL;
732   }
733
734   void UninstallExtension(const std::string& id, bool expect_success) {
735     content::WindowedNotificationObserver observer(
736         expect_success
737             ? extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
738             : extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
739         content::NotificationService::AllSources());
740     extension_service()->UninstallExtension(
741         id,
742         extensions::UNINSTALL_REASON_FOR_TESTING,
743         base::Bind(&base::DoNothing),
744         NULL);
745     observer.Wait();
746   }
747
748   void DisableExtension(const std::string& id) {
749     content::WindowedNotificationObserver observer(
750         extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
751         content::NotificationService::AllSources());
752     extension_service()->DisableExtension(id,
753                                           extensions::Extension::DISABLE_NONE);
754     observer.Wait();
755   }
756
757   void UpdateProviderPolicy(const PolicyMap& policy) {
758     provider_.UpdateChromePolicy(policy);
759     DCHECK(base::MessageLoop::current());
760     base::RunLoop loop;
761     loop.RunUntilIdle();
762   }
763
764   // Sends a mouse click at the given coordinates to the current renderer.
765   void PerformClick(int x, int y) {
766     content::WebContents* contents =
767         browser()->tab_strip_model()->GetActiveWebContents();
768     blink::WebMouseEvent click_event;
769     click_event.type = blink::WebInputEvent::MouseDown;
770     click_event.button = blink::WebMouseEvent::ButtonLeft;
771     click_event.clickCount = 1;
772     click_event.x = x;
773     click_event.y = y;
774     contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
775     click_event.type = blink::WebInputEvent::MouseUp;
776     contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
777   }
778
779   MockConfigurationPolicyProvider provider_;
780   scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
781 #if defined(OS_CHROMEOS)
782   QuitMessageLoopAfterScreenshot observer_;
783 #endif
784 };
785
786 #if defined(OS_WIN)
787 // This policy only exists on Windows.
788
789 // Sets the locale policy before the browser is started.
790 class LocalePolicyTest : public PolicyTest {
791  public:
792   LocalePolicyTest() {}
793   virtual ~LocalePolicyTest() {}
794
795   virtual void SetUpInProcessBrowserTestFixture() override {
796     PolicyTest::SetUpInProcessBrowserTestFixture();
797     PolicyMap policies;
798     policies.Set(key::kApplicationLocaleValue,
799                  POLICY_LEVEL_MANDATORY,
800                  POLICY_SCOPE_USER,
801                  new base::StringValue("fr"),
802                  NULL);
803     provider_.UpdateChromePolicy(policies);
804     // The "en-US" ResourceBundle is always loaded before this step for tests,
805     // but in this test we want the browser to load the bundle as it
806     // normally would.
807     ResourceBundle::CleanupSharedInstance();
808   }
809 };
810
811 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
812   // Verifies that the default locale can be overridden with policy.
813   EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
814   ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
815   base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
816   base::string16 title;
817   EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
818   EXPECT_EQ(french_title, title);
819
820   // Make sure this is really French and differs from the English title.
821   std::string loaded =
822       ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
823   EXPECT_EQ("en-US", loaded);
824   base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
825   EXPECT_NE(french_title, english_title);
826 }
827 #endif
828
829 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
830 #if defined(OS_WIN) && defined(USE_ASH)
831   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
832   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
833     return;
834 #endif
835
836   // Verifies that the bookmarks bar can be forced to always or never show up.
837
838   // Test starts in about:blank.
839   PrefService* prefs = browser()->profile()->GetPrefs();
840   EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
841   EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
842   EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
843
844   PolicyMap policies;
845   policies.Set(key::kBookmarkBarEnabled,
846                POLICY_LEVEL_MANDATORY,
847                POLICY_SCOPE_USER,
848                new base::FundamentalValue(true),
849                NULL);
850   UpdateProviderPolicy(policies);
851   EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
852   EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
853   EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
854
855   // The NTP has special handling of the bookmark bar.
856   ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
857   EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
858
859   policies.Set(key::kBookmarkBarEnabled,
860                POLICY_LEVEL_MANDATORY,
861                POLICY_SCOPE_USER,
862                new base::FundamentalValue(false),
863                NULL);
864   UpdateProviderPolicy(policies);
865   EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
866   EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
867   // The bookmark bar is hidden in the NTP when disabled by policy.
868   EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
869
870   policies.Clear();
871   UpdateProviderPolicy(policies);
872   EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
873   EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
874   // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
875   EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
876 }
877
878 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
879   // Verifies that cookies are deleted on shutdown. This test is split in 3
880   // parts because it spans 2 browser restarts.
881
882   Profile* profile = browser()->profile();
883   GURL url(kURL);
884   // No cookies at startup.
885   EXPECT_TRUE(content::GetCookies(profile, url).empty());
886   // Set a cookie now.
887   std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
888   EXPECT_TRUE(content::SetCookie(profile, url, value));
889   // Verify it was set.
890   EXPECT_EQ(kCookieValue, GetCookies(profile, url));
891 }
892
893 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
894   // Verify that the cookie persists across restarts.
895   EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
896   // Now set the policy and the cookie should be gone after another restart.
897   PolicyMap policies;
898   policies.Set(key::kDefaultCookiesSetting,
899                POLICY_LEVEL_MANDATORY,
900                POLICY_SCOPE_USER,
901                new base::FundamentalValue(4),
902                NULL);
903   UpdateProviderPolicy(policies);
904 }
905
906 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
907   // Verify that the cookie is gone.
908   EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
909 }
910
911 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
912   MakeRequestFail make_request_fail("search.example");
913
914   // Verifies that a default search is made using the provider configured via
915   // policy. Also checks that default search can be completely disabled.
916   const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
917   const std::string kSearchURL("http://search.example/search?q={searchTerms}");
918   const std::string kAlternateURL0(
919       "http://search.example/search#q={searchTerms}");
920   const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
921   const std::string kSearchTermsReplacementKey("zekey");
922   const std::string kImageURL("http://test.com/searchbyimage/upload");
923   const std::string kImageURLPostParams(
924       "image_content=content,image_url=http://test.com/test.png");
925   const std::string kNewTabURL("http://search.example/newtab");
926
927   TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
928       browser()->profile());
929   ui_test_utils::WaitForTemplateURLServiceToLoad(service);
930   TemplateURL* default_search = service->GetDefaultSearchProvider();
931   ASSERT_TRUE(default_search);
932   EXPECT_NE(kKeyword, default_search->keyword());
933   EXPECT_NE(kSearchURL, default_search->url());
934   EXPECT_FALSE(
935     default_search->alternate_urls().size() == 2 &&
936     default_search->alternate_urls()[0] == kAlternateURL0 &&
937     default_search->alternate_urls()[1] == kAlternateURL1 &&
938     default_search->search_terms_replacement_key() ==
939         kSearchTermsReplacementKey &&
940     default_search->image_url() == kImageURL &&
941     default_search->image_url_post_params() == kImageURLPostParams &&
942     default_search->new_tab_url() == kNewTabURL);
943
944   // Override the default search provider using policies.
945   PolicyMap policies;
946   policies.Set(key::kDefaultSearchProviderEnabled,
947                POLICY_LEVEL_MANDATORY,
948                POLICY_SCOPE_USER,
949                new base::FundamentalValue(true),
950                NULL);
951   policies.Set(key::kDefaultSearchProviderKeyword,
952                POLICY_LEVEL_MANDATORY,
953                POLICY_SCOPE_USER,
954                new base::StringValue(kKeyword),
955                NULL);
956   policies.Set(key::kDefaultSearchProviderSearchURL,
957                POLICY_LEVEL_MANDATORY,
958                POLICY_SCOPE_USER,
959                new base::StringValue(kSearchURL),
960                NULL);
961   base::ListValue* alternate_urls = new base::ListValue();
962   alternate_urls->AppendString(kAlternateURL0);
963   alternate_urls->AppendString(kAlternateURL1);
964   policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
965                POLICY_SCOPE_USER, alternate_urls, NULL);
966   policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
967                POLICY_LEVEL_MANDATORY,
968                POLICY_SCOPE_USER,
969                new base::StringValue(kSearchTermsReplacementKey),
970                NULL);
971   policies.Set(key::kDefaultSearchProviderImageURL,
972                POLICY_LEVEL_MANDATORY,
973                POLICY_SCOPE_USER,
974                new base::StringValue(kImageURL),
975                NULL);
976   policies.Set(key::kDefaultSearchProviderImageURLPostParams,
977                POLICY_LEVEL_MANDATORY,
978                POLICY_SCOPE_USER,
979                new base::StringValue(kImageURLPostParams),
980                NULL);
981   policies.Set(key::kDefaultSearchProviderNewTabURL,
982                POLICY_LEVEL_MANDATORY,
983                POLICY_SCOPE_USER,
984                new base::StringValue(kNewTabURL),
985                NULL);
986   UpdateProviderPolicy(policies);
987   default_search = service->GetDefaultSearchProvider();
988   ASSERT_TRUE(default_search);
989   EXPECT_EQ(kKeyword, default_search->keyword());
990   EXPECT_EQ(kSearchURL, default_search->url());
991   EXPECT_EQ(2U, default_search->alternate_urls().size());
992   EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
993   EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
994   EXPECT_EQ(kSearchTermsReplacementKey,
995             default_search->search_terms_replacement_key());
996   EXPECT_EQ(kImageURL, default_search->image_url());
997   EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
998   EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
999
1000   // Verify that searching from the omnibox uses kSearchURL.
1001   chrome::FocusLocationBar(browser());
1002   LocationBar* location_bar = browser()->window()->GetLocationBar();
1003   ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
1004   OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1005   EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1006   content::WebContents* web_contents =
1007       browser()->tab_strip_model()->GetActiveWebContents();
1008   GURL expected("http://search.example/search?q=stuff+to+search+for");
1009   EXPECT_EQ(expected, web_contents->GetURL());
1010
1011   // Verify that searching from the omnibox can be disabled.
1012   ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1013   policies.Set(key::kDefaultSearchProviderEnabled,
1014                POLICY_LEVEL_MANDATORY,
1015                POLICY_SCOPE_USER,
1016                new base::FundamentalValue(false),
1017                NULL);
1018   EXPECT_TRUE(service->GetDefaultSearchProvider());
1019   UpdateProviderPolicy(policies);
1020   EXPECT_FALSE(service->GetDefaultSearchProvider());
1021   ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
1022   // This means that submitting won't trigger any action.
1023   EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
1024   EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
1025 }
1026
1027 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
1028   // Add an individual proxy policy value.
1029   PolicyMap policies;
1030   policies.Set(key::kProxyServerMode,
1031                POLICY_LEVEL_MANDATORY,
1032                POLICY_SCOPE_USER,
1033                new base::FundamentalValue(3),
1034                NULL);
1035   UpdateProviderPolicy(policies);
1036
1037   // It should be removed and replaced with a dictionary.
1038   PolicyMap expected;
1039   scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
1040   expected_value->SetInteger(key::kProxyServerMode, 3);
1041   expected.Set(key::kProxySettings,
1042                POLICY_LEVEL_MANDATORY,
1043                POLICY_SCOPE_USER,
1044                expected_value.release(),
1045                NULL);
1046
1047   // Check both the browser and the profile.
1048   const PolicyMap& actual_from_browser =
1049       g_browser_process->browser_policy_connector()
1050           ->GetPolicyService()
1051           ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1052   EXPECT_TRUE(expected.Equals(actual_from_browser));
1053   const PolicyMap& actual_from_profile =
1054       ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
1055           ->policy_service()
1056           ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1057   EXPECT_TRUE(expected.Equals(actual_from_profile));
1058 }
1059
1060 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1061   // Makes the requests fail since all we want to check is that the redirection
1062   // is done properly.
1063   MakeRequestFail make_request_fail("google.com");
1064
1065   // Verifies that requests to Google Search engine with the SafeSearch
1066   // enabled set the safe=active&ssui=on parameters at the end of the query.
1067   TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1068       browser()->profile());
1069   ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1070
1071   // First check that nothing happens.
1072   content::TestNavigationObserver no_safesearch_observer(
1073       browser()->tab_strip_model()->GetActiveWebContents());
1074   chrome::FocusLocationBar(browser());
1075   LocationBar* location_bar = browser()->window()->GetLocationBar();
1076   ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1077   OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1078   no_safesearch_observer.Wait();
1079   EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1080   content::WebContents* web_contents =
1081       browser()->tab_strip_model()->GetActiveWebContents();
1082   GURL expected_without("http://google.com/");
1083   EXPECT_EQ(expected_without, web_contents->GetURL());
1084
1085   PrefService* prefs = browser()->profile()->GetPrefs();
1086   EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1087   EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1088
1089   // Override the default SafeSearch setting using policies.
1090   PolicyMap policies;
1091   policies.Set(key::kForceSafeSearch,
1092                POLICY_LEVEL_MANDATORY,
1093                POLICY_SCOPE_USER,
1094                new base::FundamentalValue(true),
1095                NULL);
1096   UpdateProviderPolicy(policies);
1097
1098   EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1099   EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1100
1101   content::TestNavigationObserver safesearch_observer(
1102       browser()->tab_strip_model()->GetActiveWebContents());
1103
1104   // Verify that searching from google.com works.
1105   chrome::FocusLocationBar(browser());
1106   ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1107   safesearch_observer.Wait();
1108   EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1109   web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1110   std::string expected_url("http://google.com/?");
1111   expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1112                   chrome::kSafeSearchSsuiParameter;
1113   GURL expected_with_parameters(expected_url);
1114   EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1115 }
1116
1117 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1118   MakeRequestFail make_request_fail("search.example");
1119
1120   chrome::EnableQueryExtractionForTesting();
1121
1122   // Verifies that a default search is made using the provider configured via
1123   // policy. Also checks that default search can be completely disabled.
1124   const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1125   const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1126   const std::string kInstantURL("http://does/not/exist");
1127   const std::string kAlternateURL0(
1128       "https://www.google.com/search#q={searchTerms}");
1129   const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1130   const std::string kSearchTermsReplacementKey(
1131       "{google:instantExtendedEnabledKey}");
1132
1133   TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1134       browser()->profile());
1135   ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1136   TemplateURL* default_search = service->GetDefaultSearchProvider();
1137   ASSERT_TRUE(default_search);
1138   EXPECT_NE(kKeyword, default_search->keyword());
1139   EXPECT_NE(kSearchURL, default_search->url());
1140   EXPECT_NE(kInstantURL, default_search->instant_url());
1141   EXPECT_FALSE(
1142     default_search->alternate_urls().size() == 2 &&
1143     default_search->alternate_urls()[0] == kAlternateURL0 &&
1144     default_search->alternate_urls()[1] == kAlternateURL1);
1145
1146   // Override the default search provider using policies.
1147   PolicyMap policies;
1148   policies.Set(key::kDefaultSearchProviderEnabled,
1149                POLICY_LEVEL_MANDATORY,
1150                POLICY_SCOPE_USER,
1151                new base::FundamentalValue(true),
1152                NULL);
1153   policies.Set(key::kDefaultSearchProviderKeyword,
1154                POLICY_LEVEL_MANDATORY,
1155                POLICY_SCOPE_USER,
1156                new base::StringValue(kKeyword),
1157                NULL);
1158   policies.Set(key::kDefaultSearchProviderSearchURL,
1159                POLICY_LEVEL_MANDATORY,
1160                POLICY_SCOPE_USER,
1161                new base::StringValue(kSearchURL),
1162                NULL);
1163   policies.Set(key::kDefaultSearchProviderInstantURL,
1164                POLICY_LEVEL_MANDATORY,
1165                POLICY_SCOPE_USER,
1166                new base::StringValue(kInstantURL),
1167                NULL);
1168   base::ListValue* alternate_urls = new base::ListValue();
1169   alternate_urls->AppendString(kAlternateURL0);
1170   alternate_urls->AppendString(kAlternateURL1);
1171   policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1172                POLICY_SCOPE_USER, alternate_urls, NULL);
1173   policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1174                POLICY_LEVEL_MANDATORY,
1175                POLICY_SCOPE_USER,
1176                new base::StringValue(kSearchTermsReplacementKey),
1177                NULL);
1178   UpdateProviderPolicy(policies);
1179   default_search = service->GetDefaultSearchProvider();
1180   ASSERT_TRUE(default_search);
1181   EXPECT_EQ(kKeyword, default_search->keyword());
1182   EXPECT_EQ(kSearchURL, default_search->url());
1183   EXPECT_EQ(kInstantURL, default_search->instant_url());
1184   EXPECT_EQ(2U, default_search->alternate_urls().size());
1185   EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1186   EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1187
1188   // Query terms replacement requires that the renderer process be a recognized
1189   // Instant renderer. Fake it.
1190   InstantService* instant_service =
1191       InstantServiceFactory::GetForProfile(browser()->profile());
1192   instant_service->AddInstantProcess(browser()->tab_strip_model()->
1193       GetActiveWebContents()->GetRenderProcessHost()->GetID());
1194
1195   // Verify that searching from the omnibox does search term replacement with
1196   // first URL pattern.
1197   chrome::FocusLocationBar(browser());
1198   LocationBar* location_bar = browser()->window()->GetLocationBar();
1199   OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1200   ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1201       "https://www.google.com/?espv=1#q=foobar");
1202   EXPECT_TRUE(
1203       browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1204   EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1205
1206   // Verify that not using espv=1 does not do search term replacement.
1207   chrome::FocusLocationBar(browser());
1208   ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1209       "https://www.google.com/?q=foobar");
1210   EXPECT_FALSE(
1211       browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1212   EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1213             omnibox_view->GetText());
1214
1215   // Verify that searching from the omnibox does search term replacement with
1216   // second URL pattern.
1217   chrome::FocusLocationBar(browser());
1218   ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1219       "https://www.google.com/search?espv=1#q=banana");
1220   EXPECT_TRUE(
1221       browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1222   EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1223
1224   // Verify that searching from the omnibox does search term replacement with
1225   // standard search URL pattern.
1226   chrome::FocusLocationBar(browser());
1227   ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1228       "https://www.google.com/search?q=tractor+parts&espv=1");
1229   EXPECT_TRUE(
1230       browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1231   EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1232
1233   // Verify that searching from the omnibox prioritizes hash over query.
1234   chrome::FocusLocationBar(browser());
1235   ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1236       "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1237   EXPECT_TRUE(
1238       browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1239   EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1240 }
1241
1242 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1243   // This test assumes Gpu access.
1244   if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1245     return;
1246
1247   ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1248   // WebGL is enabled by default.
1249   content::WebContents* contents =
1250       browser()->tab_strip_model()->GetActiveWebContents();
1251   EXPECT_TRUE(IsWebGLEnabled(contents));
1252   // Disable with a policy.
1253   PolicyMap policies;
1254   policies.Set(key::kDisable3DAPIs,
1255                POLICY_LEVEL_MANDATORY,
1256                POLICY_SCOPE_USER,
1257                new base::FundamentalValue(true),
1258                NULL);
1259   UpdateProviderPolicy(policies);
1260   // Crash and reload the tab to get a new renderer.
1261   content::CrashTab(contents);
1262   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1263   EXPECT_FALSE(IsWebGLEnabled(contents));
1264   // Enable with a policy.
1265   policies.Set(key::kDisable3DAPIs,
1266                POLICY_LEVEL_MANDATORY,
1267                POLICY_SCOPE_USER,
1268                new base::FundamentalValue(false),
1269                NULL);
1270   UpdateProviderPolicy(policies);
1271   content::CrashTab(contents);
1272   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1273   EXPECT_TRUE(IsWebGLEnabled(contents));
1274 }
1275
1276 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1277   // Verifies that SPDY can be disable by policy.
1278   EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1279   PolicyMap policies;
1280   policies.Set(key::kDisableSpdy,
1281                POLICY_LEVEL_MANDATORY,
1282                POLICY_SCOPE_USER,
1283                new base::FundamentalValue(true),
1284                NULL);
1285   UpdateProviderPolicy(policies);
1286   content::RunAllPendingInMessageLoop();
1287   EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1288   // Verify that it can be force-enabled too.
1289   browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1290   policies.Set(key::kDisableSpdy,
1291                POLICY_LEVEL_MANDATORY,
1292                POLICY_SCOPE_USER,
1293                new base::FundamentalValue(false),
1294                NULL);
1295   UpdateProviderPolicy(policies);
1296   content::RunAllPendingInMessageLoop();
1297   EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1298 }
1299
1300 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1301   // Verifies that plugins can be forced to be disabled by policy.
1302
1303   // Verify that the Flash plugin exists and that it can be enabled and disabled
1304   // by the user.
1305   std::vector<content::WebPluginInfo> plugins;
1306   GetPluginList(&plugins);
1307   const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1308   if (!flash)
1309     return;
1310   PluginPrefs* plugin_prefs =
1311       PluginPrefs::GetForProfile(browser()->profile()).get();
1312   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1313   EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1314   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1315   EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1316   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1317
1318   // Now disable it with a policy.
1319   base::ListValue disabled_plugins;
1320   disabled_plugins.Append(new base::StringValue("*Flash*"));
1321   PolicyMap policies;
1322   policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1323                POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1324   UpdateProviderPolicy(policies);
1325   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1326   // The user shouldn't be able to enable it.
1327   EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1328   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1329 }
1330
1331 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1332   // Verifies that plugins with an exception in the blacklist can be enabled.
1333
1334   // Verify that the Flash plugin exists and that it can be enabled and disabled
1335   // by the user.
1336   std::vector<content::WebPluginInfo> plugins;
1337   GetPluginList(&plugins);
1338   const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1339   if (!flash)
1340     return;
1341   PluginPrefs* plugin_prefs =
1342       PluginPrefs::GetForProfile(browser()->profile()).get();
1343   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1344
1345   // Disable all plugins.
1346   base::ListValue disabled_plugins;
1347   disabled_plugins.Append(new base::StringValue("*"));
1348   PolicyMap policies;
1349   policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1350                POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1351   UpdateProviderPolicy(policies);
1352   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1353   // The user shouldn't be able to enable it.
1354   EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1355   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1356
1357   // Now open an exception for flash.
1358   base::ListValue disabled_plugins_exceptions;
1359   disabled_plugins_exceptions.Append(new base::StringValue("*Flash*"));
1360   policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1361                POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1362   UpdateProviderPolicy(policies);
1363   // It should revert to the user's preference automatically.
1364   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1365   // And the user should be able to disable and enable again.
1366   EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1367   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1368   EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1369   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1370 }
1371
1372 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1373   // Verifies that a plugin can be force-installed with a policy.
1374   std::vector<content::WebPluginInfo> plugins;
1375   GetPluginList(&plugins);
1376   const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1377   if (!flash)
1378     return;
1379   PluginPrefs* plugin_prefs =
1380       PluginPrefs::GetForProfile(browser()->profile()).get();
1381   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1382
1383   // The user disables it and then a policy forces it to be enabled.
1384   EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1385   EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1386   base::ListValue plugin_list;
1387   plugin_list.Append(new base::StringValue(content::kFlashPluginName));
1388   PolicyMap policies;
1389   policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1390                POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1391   UpdateProviderPolicy(policies);
1392   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1393   // The user can't disable it anymore.
1394   EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1395   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1396
1397   // When a plugin is both enabled and disabled, the whitelist takes precedence.
1398   policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1399                POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1400   UpdateProviderPolicy(policies);
1401   EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1402 }
1403
1404 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1405   // Verifies that dangerous plugins can be always authorized to run with
1406   // a policy.
1407
1408   // Verify that the test page exists. It is only present in checkouts with
1409   // src-internal.
1410   if (!base::PathExists(ui_test_utils::GetTestFilePath(
1411       base::FilePath(FILE_PATH_LITERAL("plugin")),
1412       base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1413     LOG(INFO) <<
1414         "Test skipped because plugin/quicktime.html test file wasn't found.";
1415     return;
1416   }
1417
1418   ServeContentTestData();
1419   // No plugins at startup.
1420   EXPECT_EQ(0, CountPlugins());
1421
1422   content::WebContents* contents =
1423       browser()->tab_strip_model()->GetActiveWebContents();
1424   ASSERT_TRUE(contents);
1425   InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1426   ASSERT_TRUE(infobar_service);
1427   EXPECT_EQ(0u, infobar_service->infobar_count());
1428
1429   base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1430   GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1431   ui_test_utils::NavigateToURL(browser(), url);
1432   // This should have triggered the dangerous plugin infobar.
1433   ASSERT_EQ(1u, infobar_service->infobar_count());
1434   EXPECT_TRUE(
1435       infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1436   // And the plugin isn't running.
1437   EXPECT_EQ(0, CountPlugins());
1438
1439   // Now set a policy to always authorize this.
1440   PolicyMap policies;
1441   policies.Set(key::kAlwaysAuthorizePlugins,
1442                POLICY_LEVEL_MANDATORY,
1443                POLICY_SCOPE_USER,
1444                new base::FundamentalValue(true),
1445                NULL);
1446   UpdateProviderPolicy(policies);
1447   // Reloading the page shouldn't trigger the infobar this time.
1448   ui_test_utils::NavigateToURL(browser(), url);
1449   EXPECT_EQ(0u, infobar_service->infobar_count());
1450   // And the plugin started automatically.
1451   EXPECT_EQ(1, CountPlugins());
1452 }
1453
1454 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1455   // Verifies that access to the developer tools can be disabled.
1456
1457   // Open devtools.
1458   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1459   content::WebContents* contents =
1460       browser()->tab_strip_model()->GetActiveWebContents();
1461   DevToolsWindow *devtools_window =
1462       DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1463   EXPECT_TRUE(devtools_window);
1464
1465   // Disable devtools via policy.
1466   PolicyMap policies;
1467   policies.Set(key::kDeveloperToolsDisabled,
1468                POLICY_LEVEL_MANDATORY,
1469                POLICY_SCOPE_USER,
1470                new base::FundamentalValue(true),
1471                NULL);
1472   content::WindowedNotificationObserver close_observer(
1473       content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1474       content::Source<content::WebContents>(
1475           DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1476   UpdateProviderPolicy(policies);
1477   // wait for devtools close
1478   close_observer.Wait();
1479   // The existing devtools window should have closed.
1480   EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1481   // And it's not possible to open it again.
1482   EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1483   EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1484 }
1485
1486 // TODO(samarth): remove along with rest of NTP4 code.
1487 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1488 #if defined(OS_WIN) && defined(USE_ASH)
1489   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1490   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1491     return;
1492 #endif
1493
1494   // Verifies that the web store icons can be hidden from the new tab page.
1495
1496   // Open new tab page and look for the web store icons.
1497   ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1498   content::WebContents* contents =
1499     browser()->tab_strip_model()->GetActiveWebContents();
1500
1501 #if !defined(OS_CHROMEOS)
1502   // Look for web store's app ID in the apps page.
1503   EXPECT_TRUE(ContainsVisibleElement(contents,
1504                                      "ahfgeienlihckogmohjhadlkjgocpleb"));
1505 #endif
1506
1507   // The next NTP has no footer.
1508   if (ContainsVisibleElement(contents, "footer"))
1509     EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1510
1511   // Turn off the web store icons.
1512   PolicyMap policies;
1513   policies.Set(key::kHideWebStoreIcon,
1514                POLICY_LEVEL_MANDATORY,
1515                POLICY_SCOPE_USER,
1516                new base::FundamentalValue(true),
1517                NULL);
1518   UpdateProviderPolicy(policies);
1519
1520   // The web store icons should now be hidden.
1521   ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1522   EXPECT_FALSE(ContainsVisibleElement(contents,
1523                                       "ahfgeienlihckogmohjhadlkjgocpleb"));
1524   EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1525 }
1526
1527 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1528   // Verifies that the download directory can be forced by policy.
1529
1530   // Set the initial download directory.
1531   base::ScopedTempDir initial_dir;
1532   ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1533   browser()->profile()->GetPrefs()->SetFilePath(
1534       prefs::kDownloadDefaultDirectory, initial_dir.path());
1535   // Don't prompt for the download location during this test.
1536   browser()->profile()->GetPrefs()->SetBoolean(
1537       prefs::kPromptForDownload, false);
1538
1539   // Verify that downloads end up on the default directory.
1540   base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1541   DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1542   base::DieFileDie(initial_dir.path().Append(file), false);
1543
1544   // Override the download directory with the policy and verify a download.
1545   base::ScopedTempDir forced_dir;
1546   ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1547   PolicyMap policies;
1548   policies.Set(key::kDownloadDirectory,
1549                POLICY_LEVEL_MANDATORY,
1550                POLICY_SCOPE_USER,
1551                new base::StringValue(forced_dir.path().value()),
1552                NULL);
1553   UpdateProviderPolicy(policies);
1554   DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1555   // Verify that the first download location wasn't affected.
1556   EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1557 }
1558
1559 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1560   // Verifies that blacklisted extensions can't be installed.
1561   ExtensionService* service = extension_service();
1562   ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1563   ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1564   base::ListValue blacklist;
1565   blacklist.Append(new base::StringValue(kGoodCrxId));
1566   PolicyMap policies;
1567   policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1568                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1569   UpdateProviderPolicy(policies);
1570
1571   // "good.crx" is blacklisted.
1572   EXPECT_FALSE(InstallExtension(kGoodCrxName));
1573   EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1574
1575   // "adblock.crx" is not.
1576   const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1577   ASSERT_TRUE(adblock);
1578   EXPECT_EQ(kAdBlockCrxId, adblock->id());
1579   EXPECT_EQ(adblock,
1580             service->GetExtensionById(kAdBlockCrxId, true));
1581 }
1582
1583 // Flaky on windows; http://crbug.com/307994.
1584 #if defined(OS_WIN)
1585 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1586 #else
1587 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1588 #endif
1589 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1590   // Verify that a wildcard blacklist takes effect.
1591   EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1592   ExtensionService* service = extension_service();
1593   ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1594   ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1595   base::ListValue blacklist;
1596   blacklist.Append(new base::StringValue("*"));
1597   PolicyMap policies;
1598   policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1599                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1600   UpdateProviderPolicy(policies);
1601
1602   // AdBlock was automatically removed.
1603   ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1604
1605   // And can't be installed again, nor can good.crx.
1606   EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1607   EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1608   EXPECT_FALSE(InstallExtension(kGoodCrxName));
1609   EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1610 }
1611
1612 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSharedModules) {
1613   // Verifies that shared_modules are not affected by the blacklist.
1614
1615   const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
1616   const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";
1617
1618   // Make sure that "import" and "export" are available to these extension IDs
1619   // by mocking the release channel.
1620   extensions::ScopedCurrentChannel channel(chrome::VersionInfo::CHANNEL_DEV);
1621
1622   // Verify that the extensions are not installed initially.
1623   ExtensionService* service = extension_service();
1624   ASSERT_FALSE(service->GetExtensionById(kImporterId, true));
1625   ASSERT_FALSE(service->GetExtensionById(kSharedModuleId, true));
1626
1627   // Mock the webstore update URL. This is where the shared module extension
1628   // will be installed from.
1629   base::FilePath update_xml_path = base::FilePath(kTestExtensionsDir)
1630                                        .AppendASCII("policy_shared_module")
1631                                        .AppendASCII("update.xml");
1632   GURL update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path));
1633   CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1634       switches::kAppsGalleryUpdateURL, update_xml_url.spec());
1635   ui_test_utils::NavigateToURL(browser(), update_xml_url);
1636
1637   // Blacklist "*" but force-install the importer extension. The shared module
1638   // should be automatically installed too.
1639   base::ListValue blacklist;
1640   blacklist.AppendString("*");
1641   base::ListValue forcelist;
1642   forcelist.AppendString(
1643       base::StringPrintf("%s;%s", kImporterId, update_xml_url.spec().c_str()));
1644   PolicyMap policies;
1645   policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1646                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1647   policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1648                POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1649
1650   extensions::ExtensionRegistry* registry =
1651       extensions::ExtensionRegistry::Get(browser()->profile());
1652   extensions::TestExtensionRegistryObserver observe_importer(
1653       registry, kImporterId);
1654   extensions::TestExtensionRegistryObserver observe_shared_module(
1655       registry, kSharedModuleId);
1656   UpdateProviderPolicy(policies);
1657   observe_importer.WaitForExtensionLoaded();
1658   observe_shared_module.WaitForExtensionLoaded();
1659
1660   // Verify that both extensions got installed.
1661   const extensions::Extension* importer =
1662       service->GetExtensionById(kImporterId, true);
1663   ASSERT_TRUE(importer);
1664   EXPECT_EQ(kImporterId, importer->id());
1665   const extensions::Extension* shared_module =
1666       service->GetExtensionById(kSharedModuleId, true);
1667   ASSERT_TRUE(shared_module);
1668   EXPECT_EQ(kSharedModuleId, shared_module->id());
1669   EXPECT_TRUE(shared_module->is_shared_module());
1670
1671   // Verify the dependency.
1672   scoped_ptr<extensions::ExtensionSet> set =
1673       service->shared_module_service()->GetDependentExtensions(shared_module);
1674   ASSERT_TRUE(set);
1675   EXPECT_EQ(1u, set->size());
1676   EXPECT_TRUE(set->Contains(importer->id()));
1677
1678   std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
1679       extensions::SharedModuleInfo::GetImports(importer);
1680   ASSERT_EQ(1u, imports.size());
1681   EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
1682 }
1683
1684 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1685   // Verifies that the whitelist can open exceptions to the blacklist.
1686   ExtensionService* service = extension_service();
1687   ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1688   ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1689   base::ListValue blacklist;
1690   blacklist.Append(new base::StringValue("*"));
1691   base::ListValue whitelist;
1692   whitelist.Append(new base::StringValue(kGoodCrxId));
1693   PolicyMap policies;
1694   policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1695                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1696   policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1697                POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1698   UpdateProviderPolicy(policies);
1699   // "adblock.crx" is blacklisted.
1700   EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1701   EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1702   // "good.crx" has a whitelist exception.
1703   const extensions::Extension* good = InstallExtension(kGoodCrxName);
1704   ASSERT_TRUE(good);
1705   EXPECT_EQ(kGoodCrxId, good->id());
1706   EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1707   // The user can also remove this extension.
1708   UninstallExtension(kGoodCrxId, true);
1709 }
1710
1711 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1712   // Verifies that extensions that are force-installed by policies are
1713   // installed and can't be uninstalled.
1714   ExtensionService* service = extension_service();
1715   ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1716
1717   // Extensions that are force-installed come from an update URL, which defaults
1718   // to the webstore. Use a mock URL for this test with an update manifest
1719   // that includes "good_v1.crx".
1720   base::FilePath path =
1721       base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1722   GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1723
1724   // Setting the forcelist extension should install "good_v1.crx".
1725   base::ListValue forcelist;
1726   forcelist.Append(new base::StringValue(
1727       base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str())));
1728   PolicyMap policies;
1729   policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1730                POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1731   content::WindowedNotificationObserver observer(
1732       extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1733       content::NotificationService::AllSources());
1734   UpdateProviderPolicy(policies);
1735   observer.Wait();
1736   // Note: Cannot check that the notification details match the expected
1737   // exception, since the details object has already been freed prior to
1738   // the completion of observer.Wait().
1739
1740   EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1741
1742   // The user is not allowed to uninstall force-installed extensions.
1743   UninstallExtension(kGoodCrxId, false);
1744
1745   // The user is not allowed to load an unpacked extension with the
1746   // same ID as a force-installed extension.
1747   LoadUnpackedExtension(kGoodUnpackedExt, false);
1748
1749   // Loading other unpacked extensions are not blocked.
1750   LoadUnpackedExtension(kAppUnpackedExt, true);
1751
1752   const std::string old_version_number =
1753       service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1754
1755   base::FilePath test_path;
1756   ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1757
1758   TestRequestInterceptor interceptor(
1759       "update.extension",
1760       BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1761   interceptor.PushJobCallback(
1762       TestRequestInterceptor::FileJob(
1763           test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1764
1765   // Updating the force-installed extension.
1766   extensions::ExtensionUpdater* updater = service->updater();
1767   extensions::ExtensionUpdater::CheckParams params;
1768   params.install_immediately = true;
1769   content::WindowedNotificationObserver update_observer(
1770       extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1771       content::NotificationService::AllSources());
1772   updater->CheckNow(params);
1773   update_observer.Wait();
1774
1775   const base::Version* new_version =
1776       service->GetExtensionById(kGoodCrxId, true)->version();
1777   ASSERT_TRUE(new_version->IsValid());
1778   base::Version old_version(old_version_number);
1779   ASSERT_TRUE(old_version.IsValid());
1780
1781   EXPECT_EQ(1, new_version->CompareTo(old_version));
1782
1783   EXPECT_EQ(0u, interceptor.GetPendingSize());
1784
1785   // Wait until any background pages belonging to force-installed extensions
1786   // have been loaded.
1787   extensions::ProcessManager* manager =
1788       extensions::ProcessManager::Get(browser()->profile());
1789   extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1790   for (extensions::ProcessManager::ViewSet::const_iterator iter =
1791            all_views.begin();
1792        iter != all_views.end();) {
1793     if (!(*iter)->IsLoading()) {
1794       ++iter;
1795     } else {
1796       content::WebContents* web_contents =
1797           content::WebContents::FromRenderViewHost(*iter);
1798       ASSERT_TRUE(web_contents);
1799       WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1800
1801       // Test activity may have modified the set of extension processes during
1802       // message processing, so re-start the iteration to catch added/removed
1803       // processes.
1804       all_views = manager->GetAllViews();
1805       iter = all_views.begin();
1806     }
1807   }
1808
1809   // Test policy-installed extensions are reloaded when killed.
1810   BackgroundContentsService::
1811       SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1812   content::WindowedNotificationObserver extension_crashed_observer(
1813       extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1814       content::NotificationService::AllSources());
1815   content::WindowedNotificationObserver extension_loaded_observer(
1816       extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1817       content::NotificationService::AllSources());
1818   extensions::ExtensionHost* extension_host =
1819       extensions::ProcessManager::Get(browser()->profile())
1820           ->GetBackgroundHostForExtension(kGoodCrxId);
1821   base::KillProcess(extension_host->render_process_host()->GetHandle(),
1822                     content::RESULT_CODE_KILLED, false);
1823   extension_crashed_observer.Wait();
1824   extension_loaded_observer.Wait();
1825 }
1826
1827 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
1828   // Verifies that extensions that are recommended-installed by policies are
1829   // installed, can be disabled but not uninstalled.
1830   ExtensionService* service = extension_service();
1831   ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1832
1833   base::FilePath path =
1834       base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1835   GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1836
1837   // Setting the forcelist extension should install "good_v1.crx".
1838   base::DictionaryValue dict_value;
1839   dict_value.SetString(std::string(kGoodCrxId) + "." +
1840                            extensions::schema_constants::kInstallationMode,
1841                        extensions::schema_constants::kNormalInstalled);
1842   dict_value.SetString(
1843       std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
1844       url.spec());
1845   PolicyMap policies;
1846   policies.Set(key::kExtensionSettings,
1847                POLICY_LEVEL_MANDATORY,
1848                POLICY_SCOPE_USER,
1849                dict_value.DeepCopy(),
1850                NULL);
1851   content::WindowedNotificationObserver observer(
1852       extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1853       content::NotificationService::AllSources());
1854   UpdateProviderPolicy(policies);
1855   observer.Wait();
1856
1857   EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1858
1859   // The user is not allowed to uninstall recommended-installed extensions.
1860   UninstallExtension(kGoodCrxId, false);
1861
1862   // Explictly re-enables the extension.
1863   service->EnableExtension(kGoodCrxId);
1864
1865   // But the user is allowed to disable them.
1866   EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
1867   DisableExtension(kGoodCrxId);
1868   EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
1869 }
1870
1871 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1872   // Verifies that extensions are blocked if policy specifies an allowed types
1873   // list and the extension's type is not on that list.
1874   ExtensionService* service = extension_service();
1875   ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1876   ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1877
1878   base::ListValue allowed_types;
1879   allowed_types.AppendString("hosted_app");
1880   PolicyMap policies;
1881   policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1882                POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1883   UpdateProviderPolicy(policies);
1884
1885   // "good.crx" is blocked.
1886   EXPECT_FALSE(InstallExtension(kGoodCrxName));
1887   EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1888
1889   // "hosted_app.crx" is of a whitelisted type.
1890   const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1891   ASSERT_TRUE(hosted_app);
1892   EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1893   EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1894
1895   // The user can remove the extension.
1896   UninstallExtension(kHostedAppCrxId, true);
1897 }
1898
1899 // Checks that a click on an extension CRX download triggers the extension
1900 // installation prompt without further user interaction when the source is
1901 // whitelisted by policy.
1902 // Flaky on windows; http://crbug.com/295729 .
1903 #if defined(OS_WIN)
1904 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1905 #else
1906 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1907 #endif
1908 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1909   ExtensionInstallPrompt::g_auto_confirm_for_tests =
1910       ExtensionInstallPrompt::ACCEPT;
1911
1912   const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1913       base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1914   const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1915       base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1916
1917   base::ScopedTempDir download_directory;
1918   ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1919   DownloadPrefs* download_prefs =
1920       DownloadPrefs::FromBrowserContext(browser()->profile());
1921   download_prefs->SetDownloadPath(download_directory.path());
1922
1923   const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1924       FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1925   ui_test_utils::NavigateToURL(browser(), download_page_url);
1926
1927   // As long as the policy is not present, extensions are considered dangerous.
1928   content::DownloadTestObserverTerminal download_observer(
1929       content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1930       content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1931   PerformClick(0, 0);
1932   download_observer.WaitForFinished();
1933
1934   // Install the policy and trigger another download.
1935   base::ListValue install_sources;
1936   install_sources.AppendString(install_source_url.spec());
1937   install_sources.AppendString(referrer_url.spec());
1938   PolicyMap policies;
1939   policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1940                POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1941   UpdateProviderPolicy(policies);
1942
1943   content::WindowedNotificationObserver observer(
1944       extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1945       content::NotificationService::AllSources());
1946   PerformClick(1, 0);
1947   observer.Wait();
1948   // Note: Cannot check that the notification details match the expected
1949   // exception, since the details object has already been freed prior to
1950   // the completion of observer.Wait().
1951
1952   // The first extension shouldn't be present, the second should be there.
1953   EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1954   EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1955 }
1956
1957 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1958 #if defined(OS_WIN) && defined(USE_ASH)
1959   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1960   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1961     return;
1962 #endif
1963
1964   // Verifies that the homepage can be configured with policies.
1965   // Set a default, and check that the home button navigates there.
1966   browser()->profile()->GetPrefs()->SetString(
1967       prefs::kHomePage, chrome::kChromeUIPolicyURL);
1968   browser()->profile()->GetPrefs()->SetBoolean(
1969       prefs::kHomePageIsNewTabPage, false);
1970   EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1971             browser()->profile()->GetHomePage());
1972   content::WebContents* contents =
1973       browser()->tab_strip_model()->GetActiveWebContents();
1974   EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
1975   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1976   EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1977
1978   // Now override with policy.
1979   PolicyMap policies;
1980   policies.Set(key::kHomepageLocation,
1981                POLICY_LEVEL_MANDATORY,
1982                POLICY_SCOPE_USER,
1983                new base::StringValue(chrome::kChromeUICreditsURL),
1984                NULL);
1985   UpdateProviderPolicy(policies);
1986   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1987   content::WaitForLoadStop(contents);
1988   EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1989
1990   policies.Set(key::kHomepageIsNewTabPage,
1991                POLICY_LEVEL_MANDATORY,
1992                POLICY_SCOPE_USER,
1993                new base::FundamentalValue(true),
1994                NULL);
1995   UpdateProviderPolicy(policies);
1996   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1997   content::WaitForLoadStop(contents);
1998   EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1999 }
2000
2001 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
2002   // Verifies that incognito windows can't be opened when disabled by policy.
2003
2004   const BrowserList* active_browser_list =
2005       BrowserList::GetInstance(chrome::GetActiveDesktop());
2006
2007   // Disable incognito via policy and verify that incognito windows can't be
2008   // opened.
2009   EXPECT_EQ(1u, active_browser_list->size());
2010   EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2011   PolicyMap policies;
2012   policies.Set(key::kIncognitoEnabled,
2013                POLICY_LEVEL_MANDATORY,
2014                POLICY_SCOPE_USER,
2015                new base::FundamentalValue(false),
2016                NULL);
2017   UpdateProviderPolicy(policies);
2018   EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2019   EXPECT_EQ(1u, active_browser_list->size());
2020   EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2021
2022   // Enable via policy and verify that incognito windows can be opened.
2023   policies.Set(key::kIncognitoEnabled,
2024                POLICY_LEVEL_MANDATORY,
2025                POLICY_SCOPE_USER,
2026                new base::FundamentalValue(true),
2027                NULL);
2028   UpdateProviderPolicy(policies);
2029   EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2030   EXPECT_EQ(2u, active_browser_list->size());
2031   EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2032 }
2033
2034 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
2035   // Verifies that Javascript can be disabled.
2036   content::WebContents* contents =
2037       browser()->tab_strip_model()->GetActiveWebContents();
2038   EXPECT_TRUE(IsJavascriptEnabled(contents));
2039   EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2040   EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2041   EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2042
2043   // Disable Javascript via policy.
2044   PolicyMap policies;
2045   policies.Set(key::kJavascriptEnabled,
2046                POLICY_LEVEL_MANDATORY,
2047                POLICY_SCOPE_USER,
2048                new base::FundamentalValue(false),
2049                NULL);
2050   UpdateProviderPolicy(policies);
2051   // Reload the page.
2052   ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2053   EXPECT_FALSE(IsJavascriptEnabled(contents));
2054   // Developer tools still work when javascript is disabled.
2055   EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2056   EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2057   EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2058   // Javascript is always enabled for the internal pages.
2059   ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
2060   EXPECT_TRUE(IsJavascriptEnabled(contents));
2061
2062   // The javascript content setting policy overrides the javascript policy.
2063   ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2064   EXPECT_FALSE(IsJavascriptEnabled(contents));
2065   policies.Set(key::kDefaultJavaScriptSetting,
2066                POLICY_LEVEL_MANDATORY,
2067                POLICY_SCOPE_USER,
2068                new base::FundamentalValue(CONTENT_SETTING_ALLOW),
2069                NULL);
2070   UpdateProviderPolicy(policies);
2071   ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2072   EXPECT_TRUE(IsJavascriptEnabled(contents));
2073 }
2074
2075 IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
2076   PrefService* prefs = browser()->profile()->GetPrefs();
2077
2078   // Enabled by default.
2079   EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2080
2081   // Disable by old, deprecated policy.
2082   PolicyMap policies;
2083   policies.Set(key::kDnsPrefetchingEnabled,
2084                POLICY_LEVEL_MANDATORY,
2085                POLICY_SCOPE_USER,
2086                new base::FundamentalValue(false),
2087                NULL);
2088   UpdateProviderPolicy(policies);
2089
2090   EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
2091
2092   // Enabled by new policy, this should override old one.
2093   policies.Set(
2094       key::kNetworkPredictionOptions,
2095       POLICY_LEVEL_MANDATORY,
2096       POLICY_SCOPE_USER,
2097       new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
2098       NULL);
2099   UpdateProviderPolicy(policies);
2100
2101   EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2102 }
2103
2104 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
2105   // Verifies that browsing history is not saved.
2106   PolicyMap policies;
2107   policies.Set(key::kSavingBrowserHistoryDisabled,
2108                POLICY_LEVEL_MANDATORY,
2109                POLICY_SCOPE_USER,
2110                new base::FundamentalValue(true),
2111                NULL);
2112   UpdateProviderPolicy(policies);
2113   GURL url = ui_test_utils::GetTestUrl(
2114       base::FilePath(base::FilePath::kCurrentDirectory),
2115       base::FilePath(FILE_PATH_LITERAL("empty.html")));
2116   ui_test_utils::NavigateToURL(browser(), url);
2117   // Verify that the navigation wasn't saved in the history.
2118   ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
2119   EXPECT_EQ(0u, enumerator1.urls().size());
2120
2121   // Now flip the policy and try again.
2122   policies.Set(key::kSavingBrowserHistoryDisabled,
2123                POLICY_LEVEL_MANDATORY,
2124                POLICY_SCOPE_USER,
2125                new base::FundamentalValue(false),
2126                NULL);
2127   UpdateProviderPolicy(policies);
2128   ui_test_utils::NavigateToURL(browser(), url);
2129   // Verify that the navigation was saved in the history.
2130   ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
2131   ASSERT_EQ(1u, enumerator2.urls().size());
2132   EXPECT_EQ(url, enumerator2.urls()[0]);
2133 }
2134
2135 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2136 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
2137   // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2138   if (TranslateService::IsTranslateBubbleEnabled())
2139     return;
2140
2141   scoped_ptr<test::CldDataHarness> cld_data_scope =
2142       test::CreateCldDataHarness();
2143   ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init());
2144
2145   // Verifies that translate can be forced enabled or disabled by policy.
2146
2147   // Get the InfoBarService, and verify that there are no infobars on startup.
2148   content::WebContents* contents =
2149       browser()->tab_strip_model()->GetActiveWebContents();
2150   ASSERT_TRUE(contents);
2151   InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
2152   ASSERT_TRUE(infobar_service);
2153   EXPECT_EQ(0u, infobar_service->infobar_count());
2154
2155   // Force enable the translate feature.
2156   PolicyMap policies;
2157   policies.Set(key::kTranslateEnabled,
2158                POLICY_LEVEL_MANDATORY,
2159                POLICY_SCOPE_USER,
2160                new base::FundamentalValue(true),
2161                NULL);
2162   UpdateProviderPolicy(policies);
2163   // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2164   // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2165   // TranslateManager observes. This allows checking that an infobar is NOT
2166   // shown below, without polling for infobars for some indeterminate amount
2167   // of time.
2168   GURL url = ui_test_utils::GetTestUrl(
2169       base::FilePath(),
2170       base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2171   content::WindowedNotificationObserver language_observer1(
2172       chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2173       content::NotificationService::AllSources());
2174   ui_test_utils::NavigateToURL(browser(), url);
2175   language_observer1.Wait();
2176
2177   // Verify the translation detected for this tab.
2178   ChromeTranslateClient* chrome_translate_client =
2179       ChromeTranslateClient::FromWebContents(contents);
2180   ASSERT_TRUE(chrome_translate_client);
2181   translate::LanguageState& language_state =
2182       chrome_translate_client->GetLanguageState();
2183   EXPECT_EQ("fr", language_state.original_language());
2184   EXPECT_TRUE(language_state.page_needs_translation());
2185   EXPECT_FALSE(language_state.translation_pending());
2186   EXPECT_FALSE(language_state.translation_declined());
2187   EXPECT_FALSE(language_state.IsPageTranslated());
2188
2189   // Verify that the translate infobar showed up.
2190   ASSERT_EQ(1u, infobar_service->infobar_count());
2191   infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2192   translate::TranslateInfoBarDelegate* translate_infobar_delegate =
2193       infobar->delegate()->AsTranslateInfoBarDelegate();
2194   ASSERT_TRUE(translate_infobar_delegate);
2195   EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
2196             translate_infobar_delegate->translate_step());
2197   EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
2198
2199   // Now force disable translate.
2200   infobar_service->RemoveInfoBar(infobar);
2201   EXPECT_EQ(0u, infobar_service->infobar_count());
2202   policies.Set(key::kTranslateEnabled,
2203                POLICY_LEVEL_MANDATORY,
2204                POLICY_SCOPE_USER,
2205                new base::FundamentalValue(false),
2206                NULL);
2207   UpdateProviderPolicy(policies);
2208   // Navigating to the same URL now doesn't trigger an infobar.
2209   content::WindowedNotificationObserver language_observer2(
2210       chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2211       content::NotificationService::AllSources());
2212   ui_test_utils::NavigateToURL(browser(), url);
2213   language_observer2.Wait();
2214   EXPECT_EQ(0u, infobar_service->infobar_count());
2215 }
2216
2217 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
2218   // Checks that URLs can be blacklisted, and that exceptions can be made to
2219   // the blacklist.
2220
2221   // Filter |kURLS| on IO thread, so that requests to those hosts end up
2222   // as URLRequestMockHTTPJobs.
2223   const char* kURLS[] = {
2224     "http://aaa.com/empty.html",
2225     "http://bbb.com/empty.html",
2226     "http://sub.bbb.com/empty.html",
2227     "http://bbb.com/policy/blank.html",
2228   };
2229   {
2230     base::RunLoop loop;
2231     BrowserThread::PostTaskAndReply(
2232         BrowserThread::IO, FROM_HERE,
2233         base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
2234         loop.QuitClosure());
2235     loop.Run();
2236   }
2237
2238   // Verify that "bbb.com" opens before applying the blacklist.
2239   CheckCanOpenURL(browser(), kURLS[1]);
2240
2241   // Set a blacklist.
2242   base::ListValue blacklist;
2243   blacklist.Append(new base::StringValue("bbb.com"));
2244   PolicyMap policies;
2245   policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2246                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2247   UpdateProviderPolicy(policies);
2248   FlushBlacklistPolicy();
2249   // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2250   CheckCanOpenURL(browser(), kURLS[0]);
2251   for (size_t i = 1; i < arraysize(kURLS); ++i)
2252     CheckURLIsBlocked(browser(), kURLS[i]);
2253
2254   // Whitelist some sites of bbb.com.
2255   base::ListValue whitelist;
2256   whitelist.Append(new base::StringValue("sub.bbb.com"));
2257   whitelist.Append(new base::StringValue("bbb.com/policy"));
2258   policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2259                POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2260   UpdateProviderPolicy(policies);
2261   FlushBlacklistPolicy();
2262   CheckURLIsBlocked(browser(), kURLS[1]);
2263   CheckCanOpenURL(browser(), kURLS[2]);
2264   CheckCanOpenURL(browser(), kURLS[3]);
2265
2266   {
2267     base::RunLoop loop;
2268     BrowserThread::PostTaskAndReply(
2269         BrowserThread::IO, FROM_HERE,
2270         base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
2271         loop.QuitClosure());
2272     loop.Run();
2273   }
2274 }
2275
2276 #if defined(OS_MACOSX)
2277 // http://crbug.com/339240
2278 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2279 #else
2280 #define MAYBE_FileURLBlacklist FileURLBlacklist
2281 #endif
2282 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
2283   // Check that FileURLs can be blacklisted and DisabledSchemes works together
2284   // with URLblacklisting and URLwhitelisting.
2285
2286   base::FilePath test_path;
2287   PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2288   const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2289   const std::string folder_path = base_path + "apptest/";
2290   const std::string file_path1 = base_path + "title1.html";
2291   const std::string file_path2 = folder_path + "basic.html";
2292
2293   CheckCanOpenURL(browser(), file_path1.c_str());
2294   CheckCanOpenURL(browser(), file_path2.c_str());
2295
2296   // Set a blacklist for all the files.
2297   base::ListValue blacklist;
2298   blacklist.Append(new base::StringValue("file://*"));
2299   PolicyMap policies;
2300   policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2301                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2302   UpdateProviderPolicy(policies);
2303   FlushBlacklistPolicy();
2304
2305   CheckURLIsBlocked(browser(), file_path1.c_str());
2306   CheckURLIsBlocked(browser(), file_path2.c_str());
2307
2308   // Replace the URLblacklist with disabling the file scheme.
2309   blacklist.Remove(base::StringValue("file://*"), NULL);
2310   policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2311                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2312   UpdateProviderPolicy(policies);
2313   FlushBlacklistPolicy();
2314
2315   PrefService* prefs = browser()->profile()->GetPrefs();
2316   const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2317   EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2318             list_url->end());
2319
2320   base::ListValue disabledscheme;
2321   disabledscheme.Append(new base::StringValue("file"));
2322   policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2323                POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2324   UpdateProviderPolicy(policies);
2325   FlushBlacklistPolicy();
2326
2327   list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2328   EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2329             list_url->end());
2330
2331   // Whitelist one folder and blacklist an another just inside.
2332   base::ListValue whitelist;
2333   whitelist.Append(new base::StringValue(base_path));
2334   policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2335                POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2336   blacklist.Append(new base::StringValue(folder_path));
2337   policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2338                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2339   UpdateProviderPolicy(policies);
2340   FlushBlacklistPolicy();
2341
2342   CheckCanOpenURL(browser(), file_path1.c_str());
2343   CheckURLIsBlocked(browser(), file_path2.c_str());
2344 }
2345
2346 static bool IsMinSSLVersionTLS12(Profile* profile) {
2347   scoped_refptr<net::SSLConfigService> config_service(
2348       profile->GetSSLConfigService());
2349   net::SSLConfig config;
2350   config_service->GetSSLConfig(&config);
2351   return config.version_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2352 }
2353
2354 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionMin) {
2355   PrefService* prefs = g_browser_process->local_state();
2356
2357   const std::string new_value("tls1.2");
2358   const std::string default_value(prefs->GetString(prefs::kSSLVersionMin));
2359
2360   EXPECT_NE(default_value, new_value);
2361   EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2362
2363   PolicyMap policies;
2364   policies.Set(key::kSSLVersionMin,
2365                POLICY_LEVEL_MANDATORY,
2366                POLICY_SCOPE_USER,
2367                new base::StringValue(new_value),
2368                NULL);
2369   UpdateProviderPolicy(policies);
2370
2371   EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2372 }
2373
2374 static bool IsMinSSLFallbackVersionTLS12(Profile* profile) {
2375   scoped_refptr<net::SSLConfigService> config_service(
2376       profile->GetSSLConfigService());
2377   net::SSLConfig config;
2378   config_service->GetSSLConfig(&config);
2379   return config.version_fallback_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2380 }
2381
2382 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionFallbackMin) {
2383   PrefService* prefs = g_browser_process->local_state();
2384
2385   const std::string new_value("tls1.2");
2386   const std::string default_value(
2387       prefs->GetString(prefs::kSSLVersionFallbackMin));
2388
2389   EXPECT_NE(default_value, new_value);
2390   EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2391
2392   PolicyMap policies;
2393   policies.Set(key::kSSLVersionFallbackMin,
2394                POLICY_LEVEL_MANDATORY,
2395                POLICY_SCOPE_USER,
2396                new base::StringValue(new_value),
2397                NULL);
2398   UpdateProviderPolicy(policies);
2399
2400   EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2401 }
2402
2403 #if !defined(OS_MACOSX)
2404 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2405   PolicyMap policies;
2406   policies.Set(key::kFullscreenAllowed,
2407                POLICY_LEVEL_MANDATORY,
2408                POLICY_SCOPE_USER,
2409                new base::FundamentalValue(false),
2410                NULL);
2411   UpdateProviderPolicy(policies);
2412
2413   BrowserWindow* browser_window = browser()->window();
2414   ASSERT_TRUE(browser_window);
2415
2416   EXPECT_FALSE(browser_window->IsFullscreen());
2417   chrome::ToggleFullscreenMode(browser());
2418   EXPECT_FALSE(browser_window->IsFullscreen());
2419 }
2420
2421 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2422   PolicyMap policies;
2423   policies.Set(key::kFullscreenAllowed,
2424                POLICY_LEVEL_MANDATORY,
2425                POLICY_SCOPE_USER,
2426                new base::FundamentalValue(false),
2427                NULL);
2428   UpdateProviderPolicy(policies);
2429
2430   const extensions::Extension* extension =
2431       LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2432   ASSERT_TRUE(extension);
2433
2434   // Launch an app that tries to open a fullscreen window.
2435   TestAddAppWindowObserver add_window_observer(
2436       extensions::AppWindowRegistry::Get(browser()->profile()));
2437   OpenApplication(AppLaunchParams(browser()->profile(),
2438                                   extension,
2439                                   extensions::LAUNCH_CONTAINER_NONE,
2440                                   NEW_WINDOW));
2441   extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
2442   ASSERT_TRUE(window);
2443
2444   // Verify that the window is not in fullscreen mode.
2445   EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2446
2447   // Verify that the window cannot be toggled into fullscreen mode via apps
2448   // APIs.
2449   EXPECT_TRUE(content::ExecuteScript(
2450       window->web_contents(),
2451       "chrome.app.window.current().fullscreen();"));
2452   EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2453
2454   // Verify that the window cannot be toggled into fullscreen mode from within
2455   // Chrome (e.g., using keyboard accelerators).
2456   window->Fullscreen();
2457   EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2458 }
2459 #endif
2460
2461 #if defined(OS_CHROMEOS)
2462 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2463   int screenshot_count = CountScreenshots();
2464
2465   // Make sure screenshots are counted correctly.
2466   TestScreenshotFile(true);
2467   ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2468
2469   // Check if trying to take a screenshot fails when disabled by policy.
2470   TestScreenshotFile(false);
2471   ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2472 }
2473
2474 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2475   // Set up the mock observer.
2476   chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2477   scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2478   audio_handler->AddAudioObserver(test_observer.get());
2479
2480   bool prior_state = audio_handler->IsOutputMuted();
2481   // Make sure the audio is not muted and then toggle the policy and observe
2482   // if the output mute changed event is fired.
2483   audio_handler->SetOutputMute(false);
2484   EXPECT_FALSE(audio_handler->IsOutputMuted());
2485   EXPECT_EQ(1, test_observer->output_mute_changed_count());
2486   PolicyMap policies;
2487   policies.Set(key::kAudioOutputAllowed,
2488                POLICY_LEVEL_MANDATORY,
2489                POLICY_SCOPE_USER,
2490                new base::FundamentalValue(false),
2491                NULL);
2492   UpdateProviderPolicy(policies);
2493   EXPECT_TRUE(audio_handler->IsOutputMuted());
2494   // This should not change the state now and should not trigger output mute
2495   // changed event.
2496   audio_handler->SetOutputMute(false);
2497   EXPECT_TRUE(audio_handler->IsOutputMuted());
2498   EXPECT_EQ(1, test_observer->output_mute_changed_count());
2499
2500   // Toggle back and observe if the output mute changed event is fired.
2501   policies.Set(key::kAudioOutputAllowed,
2502                POLICY_LEVEL_MANDATORY,
2503                POLICY_SCOPE_USER,
2504                new base::FundamentalValue(true),
2505                NULL);
2506   UpdateProviderPolicy(policies);
2507   EXPECT_FALSE(audio_handler->IsOutputMuted());
2508   EXPECT_EQ(1, test_observer->output_mute_changed_count());
2509   audio_handler->SetOutputMute(true);
2510   EXPECT_TRUE(audio_handler->IsOutputMuted());
2511   EXPECT_EQ(2, test_observer->output_mute_changed_count());
2512   // Revert the prior state.
2513   audio_handler->SetOutputMute(prior_state);
2514   audio_handler->RemoveAudioObserver(test_observer.get());
2515 }
2516
2517 // Disabled, see http://crbug.com/315308.
2518 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2519   // Indicate that the session started 2 hours ago and no user activity has
2520   // occurred yet.
2521   g_browser_process->local_state()->SetInt64(
2522       prefs::kSessionStartTime,
2523       (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2524           .ToInternalValue());
2525 }
2526
2527 // Disabled, see http://crbug.com/315308.
2528 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2529   content::MockNotificationObserver observer;
2530   content::NotificationRegistrar registrar;
2531   registrar.Add(&observer,
2532                 chrome::NOTIFICATION_APP_TERMINATING,
2533                 content::NotificationService::AllSources());
2534
2535   // Set the session length limit to 3 hours. Verify that the session is not
2536   // terminated.
2537   EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2538       .Times(0);
2539   PolicyMap policies;
2540   policies.Set(key::kSessionLengthLimit,
2541                POLICY_LEVEL_MANDATORY,
2542                POLICY_SCOPE_USER,
2543                new base::FundamentalValue(kThreeHoursInMs),
2544                NULL);
2545   UpdateProviderPolicy(policies);
2546   base::RunLoop().RunUntilIdle();
2547   Mock::VerifyAndClearExpectations(&observer);
2548
2549   // Decrease the session length limit to 1 hour. Verify that the session is
2550   // terminated immediately.
2551   EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2552   policies.Set(key::kSessionLengthLimit,
2553                POLICY_LEVEL_MANDATORY,
2554                POLICY_SCOPE_USER,
2555                new base::FundamentalValue(kOneHourInMs),
2556                NULL);
2557   UpdateProviderPolicy(policies);
2558   base::RunLoop().RunUntilIdle();
2559   Mock::VerifyAndClearExpectations(&observer);
2560 }
2561
2562 // Disabled, see http://crbug.com/315308.
2563 IN_PROC_BROWSER_TEST_F(PolicyTest,
2564                        DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2565   // Indicate that the session started 2 hours ago and no user activity has
2566   // occurred yet.
2567   g_browser_process->local_state()->SetInt64(
2568       prefs::kSessionStartTime,
2569       (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2570           .ToInternalValue());
2571 }
2572
2573 // Disabled, see http://crbug.com/315308.
2574 IN_PROC_BROWSER_TEST_F(PolicyTest,
2575                        DISABLED_WaitForInitialUserActivityUsatisfied) {
2576   content::MockNotificationObserver observer;
2577   content::NotificationRegistrar registrar;
2578   registrar.Add(&observer,
2579                 chrome::NOTIFICATION_APP_TERMINATING,
2580                 content::NotificationService::AllSources());
2581
2582   // Require initial user activity.
2583   PolicyMap policies;
2584   policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2585                POLICY_SCOPE_USER,
2586                new base::FundamentalValue(true),
2587                NULL);
2588   UpdateProviderPolicy(policies);
2589   base::RunLoop().RunUntilIdle();
2590
2591   // Set the session length limit to 1 hour. Verify that the session is not
2592   // terminated.
2593   EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2594       .Times(0);
2595   policies.Set(key::kSessionLengthLimit,
2596                POLICY_LEVEL_MANDATORY,
2597                POLICY_SCOPE_USER,
2598                new base::FundamentalValue(kOneHourInMs),
2599                NULL);
2600   UpdateProviderPolicy(policies);
2601   base::RunLoop().RunUntilIdle();
2602   Mock::VerifyAndClearExpectations(&observer);
2603 }
2604
2605 // Disabled, see http://crbug.com/315308.
2606 IN_PROC_BROWSER_TEST_F(PolicyTest,
2607                        DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2608   // Indicate that initial user activity in this session occurred 2 hours ago.
2609   g_browser_process->local_state()->SetInt64(
2610       prefs::kSessionStartTime,
2611       (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2612           .ToInternalValue());
2613   g_browser_process->local_state()->SetBoolean(
2614       prefs::kSessionUserActivitySeen,
2615       true);
2616 }
2617
2618 // Disabled, see http://crbug.com/315308.
2619 IN_PROC_BROWSER_TEST_F(PolicyTest,
2620                        DISABLED_WaitForInitialUserActivitySatisfied) {
2621   content::MockNotificationObserver observer;
2622   content::NotificationRegistrar registrar;
2623   registrar.Add(&observer,
2624                 chrome::NOTIFICATION_APP_TERMINATING,
2625                 content::NotificationService::AllSources());
2626
2627   // Require initial user activity and set the session length limit to 3 hours.
2628   // Verify that the session is not terminated.
2629   EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2630       .Times(0);
2631   PolicyMap policies;
2632   policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2633                POLICY_SCOPE_USER,
2634                new base::FundamentalValue(true),
2635                NULL);
2636   policies.Set(key::kSessionLengthLimit,
2637                POLICY_LEVEL_MANDATORY,
2638                POLICY_SCOPE_USER,
2639                new base::FundamentalValue(kThreeHoursInMs),
2640                NULL);
2641   UpdateProviderPolicy(policies);
2642   base::RunLoop().RunUntilIdle();
2643   Mock::VerifyAndClearExpectations(&observer);
2644
2645   // Decrease the session length limit to 1 hour. Verify that the session is
2646   // terminated immediately.
2647   EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2648   policies.Set(key::kSessionLengthLimit,
2649                POLICY_LEVEL_MANDATORY,
2650                POLICY_SCOPE_USER,
2651                new base::FundamentalValue(kOneHourInMs),
2652                NULL);
2653   UpdateProviderPolicy(policies);
2654   base::RunLoop().RunUntilIdle();
2655   Mock::VerifyAndClearExpectations(&observer);
2656 }
2657
2658 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2659   // Verifies that the large cursor accessibility feature can be controlled
2660   // through policy.
2661   chromeos::AccessibilityManager* accessibility_manager =
2662       chromeos::AccessibilityManager::Get();
2663
2664   // Manually enable the large cursor.
2665   accessibility_manager->EnableLargeCursor(true);
2666   EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2667
2668   // Verify that policy overrides the manual setting.
2669   PolicyMap policies;
2670   policies.Set(key::kLargeCursorEnabled,
2671                POLICY_LEVEL_MANDATORY,
2672                POLICY_SCOPE_USER,
2673                new base::FundamentalValue(false),
2674                NULL);
2675   UpdateProviderPolicy(policies);
2676   EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2677
2678   // Verify that the large cursor cannot be enabled manually anymore.
2679   accessibility_manager->EnableLargeCursor(true);
2680   EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2681 }
2682
2683 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2684   // Verifies that the spoken feedback accessibility feature can be controlled
2685   // through policy.
2686   chromeos::AccessibilityManager* accessibility_manager =
2687       chromeos::AccessibilityManager::Get();
2688
2689   // Manually enable spoken feedback.
2690   accessibility_manager->EnableSpokenFeedback(
2691       true, ui::A11Y_NOTIFICATION_NONE);
2692   EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2693
2694   // Verify that policy overrides the manual setting.
2695   PolicyMap policies;
2696   policies.Set(key::kSpokenFeedbackEnabled,
2697                POLICY_LEVEL_MANDATORY,
2698                POLICY_SCOPE_USER,
2699                new base::FundamentalValue(false),
2700                NULL);
2701   UpdateProviderPolicy(policies);
2702   EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2703
2704   // Verify that spoken feedback cannot be enabled manually anymore.
2705   accessibility_manager->EnableSpokenFeedback(
2706       true, ui::A11Y_NOTIFICATION_NONE);
2707   EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2708 }
2709
2710 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2711   // Verifies that the high contrast mode accessibility feature can be
2712   // controlled through policy.
2713   chromeos::AccessibilityManager* accessibility_manager =
2714       chromeos::AccessibilityManager::Get();
2715
2716   // Manually enable high contrast mode.
2717   accessibility_manager->EnableHighContrast(true);
2718   EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2719
2720   // Verify that policy overrides the manual setting.
2721   PolicyMap policies;
2722   policies.Set(key::kHighContrastEnabled,
2723                POLICY_LEVEL_MANDATORY,
2724                POLICY_SCOPE_USER,
2725                new base::FundamentalValue(false),
2726                NULL);
2727   UpdateProviderPolicy(policies);
2728   EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2729
2730   // Verify that high contrast mode cannot be enabled manually anymore.
2731   accessibility_manager->EnableHighContrast(true);
2732   EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2733 }
2734
2735 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2736   // Verifies that the screen magnifier can be disabled through policy.
2737   chromeos::MagnificationManager* magnification_manager =
2738       chromeos::MagnificationManager::Get();
2739
2740   // Manually enable the full-screen magnifier.
2741   magnification_manager->SetMagnifierType(ui::MAGNIFIER_FULL);
2742   magnification_manager->SetMagnifierEnabled(true);
2743   EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2744   EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2745
2746   // Verify that policy overrides the manual setting.
2747   PolicyMap policies;
2748   policies.Set(key::kScreenMagnifierType,
2749                POLICY_LEVEL_MANDATORY,
2750                POLICY_SCOPE_USER,
2751                new base::FundamentalValue(0),
2752                NULL);
2753   UpdateProviderPolicy(policies);
2754   EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2755
2756   // Verify that the screen magnifier cannot be enabled manually anymore.
2757   magnification_manager->SetMagnifierEnabled(true);
2758   EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2759 }
2760
2761 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2762   // Verifies that the full-screen magnifier can be enabled through policy.
2763   chromeos::MagnificationManager* magnification_manager =
2764       chromeos::MagnificationManager::Get();
2765
2766   // Verify that the screen magnifier is initially disabled.
2767   EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2768
2769   // Verify that policy can enable the full-screen magnifier.
2770   PolicyMap policies;
2771   policies.Set(key::kScreenMagnifierType,
2772                POLICY_LEVEL_MANDATORY,
2773                POLICY_SCOPE_USER,
2774                new base::FundamentalValue(ui::MAGNIFIER_FULL),
2775                NULL);
2776   UpdateProviderPolicy(policies);
2777   EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2778   EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2779
2780   // Verify that the screen magnifier cannot be disabled manually anymore.
2781   magnification_manager->SetMagnifierEnabled(false);
2782   EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2783 }
2784
2785 IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
2786   // Verifies that the on-screen keyboard accessibility feature can be
2787   // controlled through policy.
2788   chromeos::AccessibilityManager* accessibility_manager =
2789       chromeos::AccessibilityManager::Get();
2790
2791   // Manually enable the on-screen keyboard.
2792   accessibility_manager->EnableVirtualKeyboard(true);
2793   EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2794
2795   // Verify that policy overrides the manual setting.
2796   PolicyMap policies;
2797   policies.Set(key::kVirtualKeyboardEnabled,
2798                POLICY_LEVEL_MANDATORY,
2799                POLICY_SCOPE_USER,
2800                new base::FundamentalValue(false),
2801                NULL);
2802   UpdateProviderPolicy(policies);
2803   EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2804
2805   // Verify that the on-screen keyboard cannot be enabled manually anymore.
2806   accessibility_manager->EnableVirtualKeyboard(true);
2807   EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2808 }
2809
2810 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
2811   // Verify keyboard disabled by default.
2812   EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2813   // Verify keyboard can be toggled by default.
2814   keyboard::SetTouchKeyboardEnabled(true);
2815   EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2816   keyboard::SetTouchKeyboardEnabled(false);
2817   EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2818
2819   // Verify enabling the policy takes effect immediately and that that user
2820   // cannot disable the keyboard..
2821   PolicyMap policies;
2822   policies.Set(key::kTouchVirtualKeyboardEnabled,
2823                POLICY_LEVEL_MANDATORY,
2824                POLICY_SCOPE_USER,
2825                new base::FundamentalValue(true),
2826                NULL);
2827   UpdateProviderPolicy(policies);
2828   EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2829   keyboard::SetTouchKeyboardEnabled(false);
2830   EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2831
2832   // Verify that disabling the policy takes effect immediately and that the user
2833   // cannot enable the keyboard.
2834   policies.Set(key::kTouchVirtualKeyboardEnabled,
2835                POLICY_LEVEL_MANDATORY,
2836                POLICY_SCOPE_USER,
2837                new base::FundamentalValue(false),
2838                NULL);
2839   UpdateProviderPolicy(policies);
2840   EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2841   keyboard::SetTouchKeyboardEnabled(true);
2842   EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2843 }
2844
2845 #endif
2846
2847 namespace {
2848
2849 static const char* kRestoredURLs[] = {
2850   "http://aaa.com/empty.html",
2851   "http://bbb.com/empty.html",
2852 };
2853
2854 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2855   return s.empty() || s[0] != '-';
2856 }
2857
2858 }  // namespace
2859
2860 // Similar to PolicyTest but allows setting policies before the browser is
2861 // created. Each test parameter is a method that sets up the early policies
2862 // and stores the expected startup URLs in |expected_urls_|.
2863 class RestoreOnStartupPolicyTest
2864     : public PolicyTest,
2865       public testing::WithParamInterface<
2866           void (RestoreOnStartupPolicyTest::*)(void)> {
2867  public:
2868   RestoreOnStartupPolicyTest() {}
2869   virtual ~RestoreOnStartupPolicyTest() {}
2870
2871 #if defined(OS_CHROMEOS)
2872   virtual void SetUpCommandLine(CommandLine* command_line) override {
2873     // TODO(nkostylev): Investigate if we can remove this switch.
2874     command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2875     PolicyTest::SetUpCommandLine(command_line);
2876   }
2877 #endif
2878
2879   void SetUpInProcessBrowserTestFixture() override {
2880     PolicyTest::SetUpInProcessBrowserTestFixture();
2881     // Set early policies now, before the browser is created.
2882     (this->*(GetParam()))();
2883
2884     // Remove the non-switch arguments, so that session restore kicks in for
2885     // these tests.
2886     CommandLine* command_line = CommandLine::ForCurrentProcess();
2887     CommandLine::StringVector argv = command_line->argv();
2888     argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2889                argv.end());
2890     command_line->InitFromArgv(argv);
2891     ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2892                            command_line->argv().begin()));
2893   }
2894
2895   void SetUpOnMainThread() override {
2896     BrowserThread::PostTask(
2897         BrowserThread::IO,
2898         FROM_HERE,
2899         base::Bind(
2900             RedirectHostsToTestData, kRestoredURLs, arraysize(kRestoredURLs)));
2901   }
2902
2903   void HomepageIsNotNTP() {
2904     // Verifies that policy can set the startup pages to the homepage, when
2905     // the homepage is not the NTP.
2906     PolicyMap policies;
2907     policies.Set(
2908         key::kRestoreOnStartup,
2909         POLICY_LEVEL_MANDATORY,
2910         POLICY_SCOPE_USER,
2911         new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
2912         NULL);
2913     policies.Set(key::kHomepageIsNewTabPage,
2914                  POLICY_LEVEL_MANDATORY,
2915                  POLICY_SCOPE_USER,
2916                  new base::FundamentalValue(false),
2917                  NULL);
2918     policies.Set(key::kHomepageLocation,
2919                  POLICY_LEVEL_MANDATORY,
2920                  POLICY_SCOPE_USER,
2921                  new base::StringValue(kRestoredURLs[1]),
2922                  NULL);
2923     provider_.UpdateChromePolicy(policies);
2924
2925     expected_urls_.push_back(GURL(kRestoredURLs[1]));
2926   }
2927
2928   void HomepageIsNTP() {
2929     // Verifies that policy can set the startup pages to the homepage, when
2930     // the homepage is the NTP.
2931     PolicyMap policies;
2932     policies.Set(
2933         key::kRestoreOnStartup,
2934         POLICY_LEVEL_MANDATORY,
2935         POLICY_SCOPE_USER,
2936         new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
2937         NULL);
2938     policies.Set(key::kHomepageIsNewTabPage,
2939                  POLICY_LEVEL_MANDATORY,
2940                  POLICY_SCOPE_USER,
2941                  new base::FundamentalValue(true),
2942                  NULL);
2943     provider_.UpdateChromePolicy(policies);
2944
2945     expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2946   }
2947
2948   void ListOfURLs() {
2949     // Verifies that policy can set the startup pages to a list of URLs.
2950     base::ListValue urls;
2951     for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2952       urls.Append(new base::StringValue(kRestoredURLs[i]));
2953       expected_urls_.push_back(GURL(kRestoredURLs[i]));
2954     }
2955     PolicyMap policies;
2956     policies.Set(key::kRestoreOnStartup,
2957                  POLICY_LEVEL_MANDATORY,
2958                  POLICY_SCOPE_USER,
2959                  new base::FundamentalValue(SessionStartupPref::kPrefValueURLs),
2960                  NULL);
2961     policies.Set(
2962         key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2963         urls.DeepCopy(), NULL);
2964     provider_.UpdateChromePolicy(policies);
2965   }
2966
2967   void NTP() {
2968     // Verifies that policy can set the startup page to the NTP.
2969     PolicyMap policies;
2970     policies.Set(
2971         key::kRestoreOnStartup,
2972         POLICY_LEVEL_MANDATORY,
2973         POLICY_SCOPE_USER,
2974         new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab),
2975         NULL);
2976     provider_.UpdateChromePolicy(policies);
2977     expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2978   }
2979
2980   void Last() {
2981     // Verifies that policy can set the startup pages to the last session.
2982     PolicyMap policies;
2983     policies.Set(key::kRestoreOnStartup,
2984                  POLICY_LEVEL_MANDATORY,
2985                  POLICY_SCOPE_USER,
2986                  new base::FundamentalValue(SessionStartupPref::kPrefValueLast),
2987                  NULL);
2988     provider_.UpdateChromePolicy(policies);
2989     // This should restore the tabs opened at PRE_RunTest below.
2990     for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2991       expected_urls_.push_back(GURL(kRestoredURLs[i]));
2992   }
2993
2994   std::vector<GURL> expected_urls_;
2995 };
2996
2997 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2998   // Open some tabs to verify if they are restored after the browser restarts.
2999   // Most policy settings override this, except kPrefValueLast which enforces
3000   // a restore.
3001   ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
3002   for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
3003     content::WindowedNotificationObserver observer(
3004         content::NOTIFICATION_LOAD_STOP,
3005         content::NotificationService::AllSources());
3006     chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
3007                                   ui::PAGE_TRANSITION_LINK);
3008     observer.Wait();
3009   }
3010 }
3011
3012 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
3013 #if defined(OS_WIN) && defined(USE_ASH)
3014   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3015   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
3016     return;
3017 #endif
3018
3019   TabStripModel* model = browser()->tab_strip_model();
3020   int size = static_cast<int>(expected_urls_.size());
3021   EXPECT_EQ(size, model->count());
3022   for (int i = 0; i < size && i < model->count(); ++i) {
3023     EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
3024   }
3025 }
3026
3027 INSTANTIATE_TEST_CASE_P(
3028     RestoreOnStartupPolicyTestInstance,
3029     RestoreOnStartupPolicyTest,
3030     testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
3031                     &RestoreOnStartupPolicyTest::HomepageIsNTP,
3032                     &RestoreOnStartupPolicyTest::ListOfURLs,
3033                     &RestoreOnStartupPolicyTest::NTP,
3034                     &RestoreOnStartupPolicyTest::Last));
3035
3036 // Similar to PolicyTest but sets a couple of policies before the browser is
3037 // started.
3038 class PolicyStatisticsCollectorTest : public PolicyTest {
3039  public:
3040   PolicyStatisticsCollectorTest() {}
3041   ~PolicyStatisticsCollectorTest() override {}
3042
3043   void SetUpInProcessBrowserTestFixture() override {
3044     PolicyTest::SetUpInProcessBrowserTestFixture();
3045     PolicyMap policies;
3046     policies.Set(key::kShowHomeButton,
3047                  POLICY_LEVEL_MANDATORY,
3048                  POLICY_SCOPE_USER,
3049                  new base::FundamentalValue(true),
3050                  NULL);
3051     policies.Set(key::kBookmarkBarEnabled,
3052                  POLICY_LEVEL_MANDATORY,
3053                  POLICY_SCOPE_USER,
3054                  new base::FundamentalValue(false),
3055                  NULL);
3056     policies.Set(key::kHomepageLocation,
3057                  POLICY_LEVEL_MANDATORY,
3058                  POLICY_SCOPE_USER,
3059                  new base::StringValue("http://chromium.org"),
3060                  NULL);
3061     provider_.UpdateChromePolicy(policies);
3062   }
3063 };
3064
3065 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
3066   // Verifies that policy usage histograms are collected at startup.
3067
3068   // BrowserPolicyConnector::Init() has already been called. Make sure the
3069   // CompleteInitialization() task has executed as well.
3070   content::RunAllPendingInMessageLoop();
3071
3072   GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
3073                                std::string(url::kStandardSchemeSeparator) +
3074                                std::string(content::kChromeUIHistogramHost));
3075   ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
3076   content::WebContents* contents =
3077       browser()->tab_strip_model()->GetActiveWebContents();
3078   std::string text;
3079   ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3080       contents,
3081       "var nodes = document.querySelectorAll('body > pre');"
3082       "var result = '';"
3083       "for (var i = 0; i < nodes.length; ++i) {"
3084       "  var text = nodes[i].innerHTML;"
3085       "  if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3086       "    result = text;"
3087       "    break;"
3088       "  }"
3089       "}"
3090       "domAutomationController.send(result);",
3091       &text));
3092   ASSERT_FALSE(text.empty());
3093   const std::string kExpectedLabel =
3094       "Histogram: Enterprise.Policies recorded 3 samples";
3095   EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
3096   // HomepageLocation has policy ID 1.
3097   EXPECT_NE(std::string::npos, text.find("<br>1   ---"));
3098   // ShowHomeButton has policy ID 35.
3099   EXPECT_NE(std::string::npos, text.find("<br>35  ---"));
3100   // BookmarkBarEnabled has policy ID 82.
3101   EXPECT_NE(std::string::npos, text.find("<br>82  ---"));
3102 }
3103
3104 class MediaStreamDevicesControllerBrowserTest
3105     : public PolicyTest,
3106       public testing::WithParamInterface<bool> {
3107  public:
3108   MediaStreamDevicesControllerBrowserTest()
3109       : request_url_allowed_via_whitelist_(false) {
3110     policy_value_ = GetParam();
3111   }
3112   virtual ~MediaStreamDevicesControllerBrowserTest() {}
3113
3114   // Configure a given policy map.
3115   // The |policy_name| is the name of either the audio or video capture allow
3116   // policy and must never be NULL.
3117   // |whitelist_policy| and |allow_rule| are optional.  If NULL, no whitelist
3118   // policy is set.  If non-NULL, the request_url_ will be set to be non empty
3119   // and the whitelist policy is set to contain either the |allow_rule| (if
3120   // non-NULL) or an "allow all" wildcard.
3121   void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
3122                           const char* whitelist_policy,
3123                           const char* allow_rule) {
3124     policies->Set(policy_name,
3125                   POLICY_LEVEL_MANDATORY,
3126                   POLICY_SCOPE_USER,
3127                   new base::FundamentalValue(policy_value_),
3128                   NULL);
3129
3130     if (whitelist_policy) {
3131       // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3132       // in the media exceptions UI.
3133       // See discussion here: https://codereview.chromium.org/15738004/
3134       CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
3135
3136       // Add an entry to the whitelist that allows the specified URL regardless
3137       // of the setting of kAudioCapturedAllowed.
3138       request_url_ = GURL("http://www.example.com/foo");
3139       base::ListValue* list = new base::ListValue();
3140       if (allow_rule) {
3141         list->AppendString(allow_rule);
3142         request_url_allowed_via_whitelist_ = true;
3143       } else {
3144         list->AppendString(ContentSettingsPattern::Wildcard().ToString());
3145         // We should ignore all wildcard entries in the whitelist, so even
3146         // though we've added an entry, it should be ignored and our expectation
3147         // is that the request has not been allowed via the whitelist.
3148         request_url_allowed_via_whitelist_ = false;
3149       }
3150       policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
3151                     POLICY_SCOPE_USER, list, NULL);
3152     }
3153   }
3154
3155   void Accept(const content::MediaStreamDevices& devices,
3156               content::MediaStreamRequestResult result,
3157               scoped_ptr<content::MediaStreamUI> ui) {
3158     if (policy_value_ || request_url_allowed_via_whitelist_) {
3159       ASSERT_EQ(1U, devices.size());
3160       ASSERT_EQ("fake_dev", devices[0].id);
3161     } else {
3162       ASSERT_EQ(0U, devices.size());
3163     }
3164   }
3165
3166   void FinishAudioTest() {
3167     content::MediaStreamRequest request(0, 0, 0,
3168                                         request_url_.GetOrigin(), false,
3169                                         content::MEDIA_DEVICE_ACCESS,
3170                                         std::string(), std::string(),
3171                                         content::MEDIA_DEVICE_AUDIO_CAPTURE,
3172                                         content::MEDIA_NO_SERVICE);
3173     // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3174     // and microphone permissions at the same time.
3175     MediaStreamDevicesController controller(
3176         browser()->tab_strip_model()->GetActiveWebContents(), request,
3177         base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3178     controller.Accept(false);
3179
3180     base::MessageLoop::current()->QuitWhenIdle();
3181   }
3182
3183   void FinishVideoTest() {
3184     // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3185     // and microphone permissions at the same time.
3186     content::MediaStreamRequest request(0, 0, 0,
3187                                         request_url_.GetOrigin(), false,
3188                                         content::MEDIA_DEVICE_ACCESS,
3189                                         std::string(),
3190                                         std::string(),
3191                                         content::MEDIA_NO_SERVICE,
3192                                         content::MEDIA_DEVICE_VIDEO_CAPTURE);
3193     MediaStreamDevicesController controller(
3194         browser()->tab_strip_model()->GetActiveWebContents(), request,
3195         base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3196     controller.Accept(false);
3197
3198     base::MessageLoop::current()->QuitWhenIdle();
3199   }
3200
3201   bool policy_value_;
3202   bool request_url_allowed_via_whitelist_;
3203   GURL request_url_;
3204   static const char kExampleRequestPattern[];
3205 };
3206
3207 // static
3208 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
3209     "http://[*.]example.com/";
3210
3211 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3212                        AudioCaptureAllowed) {
3213   content::MediaStreamDevices audio_devices;
3214   content::MediaStreamDevice fake_audio_device(
3215       content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3216   audio_devices.push_back(fake_audio_device);
3217
3218   PolicyMap policies;
3219   ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
3220   UpdateProviderPolicy(policies);
3221
3222   content::BrowserThread::PostTaskAndReply(
3223       content::BrowserThread::IO, FROM_HERE,
3224       base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3225                  base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3226                  audio_devices),
3227       base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3228                  this));
3229
3230   base::MessageLoop::current()->Run();
3231 }
3232
3233 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3234                        AudioCaptureAllowedUrls) {
3235   content::MediaStreamDevices audio_devices;
3236   content::MediaStreamDevice fake_audio_device(
3237       content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3238   audio_devices.push_back(fake_audio_device);
3239
3240   const char* allow_pattern[] = {
3241     kExampleRequestPattern,
3242     // This will set an allow-all policy whitelist.  Since we do not allow
3243     // setting an allow-all entry in the whitelist, this entry should be ignored
3244     // and therefore the request should be denied.
3245     NULL,
3246   };
3247
3248   for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3249     PolicyMap policies;
3250     ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
3251                        key::kAudioCaptureAllowedUrls, allow_pattern[i]);
3252     UpdateProviderPolicy(policies);
3253
3254     content::BrowserThread::PostTaskAndReply(
3255         content::BrowserThread::IO, FROM_HERE,
3256         base::Bind(
3257             &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3258             base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3259             audio_devices),
3260         base::Bind(
3261             &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3262             this));
3263
3264     base::MessageLoop::current()->Run();
3265   }
3266 }
3267
3268 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3269                        VideoCaptureAllowed) {
3270   content::MediaStreamDevices video_devices;
3271   content::MediaStreamDevice fake_video_device(
3272       content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3273   video_devices.push_back(fake_video_device);
3274
3275   PolicyMap policies;
3276   ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
3277   UpdateProviderPolicy(policies);
3278
3279   content::BrowserThread::PostTaskAndReply(
3280       content::BrowserThread::IO, FROM_HERE,
3281       base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3282                  base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3283                  video_devices),
3284       base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3285                  this));
3286
3287   base::MessageLoop::current()->Run();
3288 }
3289
3290 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3291                        VideoCaptureAllowedUrls) {
3292   content::MediaStreamDevices video_devices;
3293   content::MediaStreamDevice fake_video_device(
3294       content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3295   video_devices.push_back(fake_video_device);
3296
3297   const char* allow_pattern[] = {
3298     kExampleRequestPattern,
3299     // This will set an allow-all policy whitelist.  Since we do not allow
3300     // setting an allow-all entry in the whitelist, this entry should be ignored
3301     // and therefore the request should be denied.
3302     NULL,
3303   };
3304
3305   for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3306     PolicyMap policies;
3307     ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
3308                        key::kVideoCaptureAllowedUrls, allow_pattern[i]);
3309     UpdateProviderPolicy(policies);
3310
3311     content::BrowserThread::PostTaskAndReply(
3312         content::BrowserThread::IO, FROM_HERE,
3313         base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3314             base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3315             video_devices),
3316         base::Bind(
3317             &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3318             this));
3319
3320     base::MessageLoop::current()->Run();
3321   }
3322 }
3323
3324 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
3325                         MediaStreamDevicesControllerBrowserTest,
3326                         testing::Bool());
3327
3328 #if !defined(OS_CHROMEOS)
3329 // Similar to PolicyTest but sets the proper policy before the browser is
3330 // started.
3331 class PolicyVariationsServiceTest : public PolicyTest {
3332  public:
3333   void SetUpInProcessBrowserTestFixture() override {
3334     PolicyTest::SetUpInProcessBrowserTestFixture();
3335     PolicyMap policies;
3336     policies.Set(key::kVariationsRestrictParameter,
3337                  POLICY_LEVEL_MANDATORY,
3338                  POLICY_SCOPE_USER,
3339                  new base::StringValue("restricted"),
3340                  NULL);
3341     provider_.UpdateChromePolicy(policies);
3342   }
3343 };
3344
3345 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
3346   const std::string default_variations_url =
3347       chrome_variations::VariationsService::
3348           GetDefaultVariationsServerURLForTesting();
3349
3350   const GURL url =
3351       chrome_variations::VariationsService::GetVariationsServerURL(
3352           g_browser_process->local_state());
3353   EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
3354   std::string value;
3355   EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
3356   EXPECT_EQ("restricted", value);
3357 }
3358
3359 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
3360   base::ListValue blacklist;
3361   blacklist.Append(new base::StringValue("host.name"));
3362   PolicyMap policies;
3363   policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3364                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3365   UpdateProviderPolicy(policies);
3366
3367   PrefService* prefs = browser()->profile()->GetPrefs();
3368   EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3369       prefs, "host.name"));
3370   EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3371       prefs, "other.host.name"));
3372 }
3373
3374 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
3375   base::ListValue blacklist;
3376   blacklist.Append(new base::StringValue("*"));
3377   PolicyMap policies;
3378   policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3379                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3380   UpdateProviderPolicy(policies);
3381
3382   PrefService* prefs = browser()->profile()->GetPrefs();
3383   EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3384       prefs, "host.name"));
3385   EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3386       prefs, "other.host.name"));
3387 }
3388
3389 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3390   base::ListValue blacklist;
3391   blacklist.Append(new base::StringValue("*"));
3392   base::ListValue whitelist;
3393   whitelist.Append(new base::StringValue("host.name"));
3394   PolicyMap policies;
3395   policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3396                POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3397   policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3398                POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3399   UpdateProviderPolicy(policies);
3400
3401   PrefService* prefs = browser()->profile()->GetPrefs();
3402   EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3403       prefs, "host.name"));
3404   EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3405       prefs, "other.host.name"));
3406 }
3407
3408 IN_PROC_BROWSER_TEST_F(PolicyTest,
3409                        EnableDeprecatedWebPlatformFeatures_ShowModalDialog) {
3410   base::ListValue enabled_features;
3411   enabled_features.Append(new base::StringValue(
3412       "ShowModalDialog_EffectiveUntil20150430"));
3413   PolicyMap policies;
3414   policies.Set(key::kEnableDeprecatedWebPlatformFeatures,
3415                POLICY_LEVEL_MANDATORY,
3416                POLICY_SCOPE_USER,
3417                enabled_features.DeepCopy(),
3418                NULL);
3419   UpdateProviderPolicy(policies);
3420
3421   // Policy only takes effect on new browsers, not existing browsers, so create
3422   // a new browser.
3423   Browser* browser2 = CreateBrowser(browser()->profile());
3424   ui_test_utils::NavigateToURL(browser2, GURL(url::kAboutBlankURL));
3425   bool result = false;
3426   EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
3427       browser2->tab_strip_model()->GetActiveWebContents(),
3428       "domAutomationController.send(window.showModalDialog !== undefined);",
3429       &result));
3430   EXPECT_TRUE(result);
3431 }
3432
3433 #endif  // !defined(CHROME_OS)
3434
3435 }  // namespace policy