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