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