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