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