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