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