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