policy_browsertest.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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_paths.h"
98#include "content/public/common/page_transition_types.h"
99#include "content/public/common/process_type.h"
100#include "content/public/common/url_constants.h"
101#include "content/public/common/webplugininfo.h"
102#include "content/public/test/browser_test_utils.h"
103#include "content/public/test/download_test_observer.h"
104#include "content/public/test/mock_notification_observer.h"
105#include "content/public/test/test_navigation_observer.h"
106#include "content/public/test/test_utils.h"
107#include "content/test/net/url_request_failed_job.h"
108#include "content/test/net/url_request_mock_http_job.h"
109#include "grit/generated_resources.h"
110#include "net/base/net_errors.h"
111#include "net/base/net_util.h"
112#include "net/base/url_util.h"
113#include "net/http/http_stream_factory.h"
114#include "net/url_request/url_request.h"
115#include "net/url_request/url_request_filter.h"
116#include "policy/policy_constants.h"
117#include "testing/gmock/include/gmock/gmock.h"
118#include "testing/gtest/include/gtest/gtest.h"
119#include "third_party/WebKit/public/web/WebInputEvent.h"
120#include "ui/base/l10n/l10n_util.h"
121#include "ui/base/resource/resource_bundle.h"
122#include "url/gurl.h"
123#include "webkit/plugins/plugin_constants.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(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::Create(extension_service(), NULL);
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
711  TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
712      browser()->profile());
713  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
714  TemplateURL* default_search = service->GetDefaultSearchProvider();
715  ASSERT_TRUE(default_search);
716  EXPECT_NE(kKeyword, default_search->keyword());
717  EXPECT_NE(kSearchURL, default_search->url());
718  EXPECT_FALSE(
719    default_search->alternate_urls().size() == 2 &&
720    default_search->alternate_urls()[0] == kAlternateURL0 &&
721    default_search->alternate_urls()[1] == kAlternateURL1 &&
722    default_search->search_terms_replacement_key() ==
723        kSearchTermsReplacementKey &&
724    default_search->image_url() == kImageURL &&
725    default_search->image_url_post_params() == kImageURLPostParams);
726
727  // Override the default search provider using policies.
728  PolicyMap policies;
729  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
730               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
731  policies.Set(key::kDefaultSearchProviderKeyword,
732               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
733               base::Value::CreateStringValue(kKeyword), NULL);
734  policies.Set(key::kDefaultSearchProviderSearchURL,
735               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
736               base::Value::CreateStringValue(kSearchURL), NULL);
737  base::ListValue* alternate_urls = new base::ListValue();
738  alternate_urls->AppendString(kAlternateURL0);
739  alternate_urls->AppendString(kAlternateURL1);
740  policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
741               POLICY_SCOPE_USER, alternate_urls, NULL);
742  policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
743               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
744               base::Value::CreateStringValue(kSearchTermsReplacementKey),
745               NULL);
746  policies.Set(key::kDefaultSearchProviderImageURL,
747               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
748               base::Value::CreateStringValue(kImageURL),
749               NULL);
750  policies.Set(key::kDefaultSearchProviderImageURLPostParams,
751               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
752               base::Value::CreateStringValue(kImageURLPostParams),
753               NULL);
754  UpdateProviderPolicy(policies);
755  default_search = service->GetDefaultSearchProvider();
756  ASSERT_TRUE(default_search);
757  EXPECT_EQ(kKeyword, default_search->keyword());
758  EXPECT_EQ(kSearchURL, default_search->url());
759  EXPECT_EQ(2U, default_search->alternate_urls().size());
760  EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
761  EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
762  EXPECT_EQ(kSearchTermsReplacementKey,
763            default_search->search_terms_replacement_key());
764  EXPECT_EQ(kImageURL, default_search->image_url());
765  EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
766
767  // Verify that searching from the omnibox uses kSearchURL.
768  chrome::FocusLocationBar(browser());
769  LocationBar* location_bar = browser()->window()->GetLocationBar();
770  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
771  OmniboxEditModel* model = location_bar->GetLocationEntry()->model();
772  EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
773  content::WebContents* web_contents =
774      browser()->tab_strip_model()->GetActiveWebContents();
775  GURL expected("http://search.example/search?q=stuff+to+search+for");
776  EXPECT_EQ(expected, web_contents->GetURL());
777
778  // Verify that searching from the omnibox can be disabled.
779  ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
780  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
781               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
782  EXPECT_TRUE(service->GetDefaultSearchProvider());
783  UpdateProviderPolicy(policies);
784  EXPECT_FALSE(service->GetDefaultSearchProvider());
785  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
786  // This means that submitting won't trigger any action.
787  EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
788  EXPECT_EQ(GURL(content::kAboutBlankURL), web_contents->GetURL());
789}
790
791IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
792  // Makes the requests fail since all we want to check is that the redirection
793  // is done properly.
794  MakeRequestFail make_request_fail("google.com");
795
796  // Verifies that requests to Google Search engine with the SafeSearch
797  // enabled set the safe=active&ssui=on parameters at the end of the query.
798  TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
799      browser()->profile());
800  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
801
802  // First check that nothing happens.
803  content::TestNavigationObserver no_safesearch_observer(
804      browser()->tab_strip_model()->GetActiveWebContents());
805  chrome::FocusLocationBar(browser());
806  LocationBar* location_bar = browser()->window()->GetLocationBar();
807  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
808  OmniboxEditModel* model = location_bar->GetLocationEntry()->model();
809  no_safesearch_observer.Wait();
810  EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
811  content::WebContents* web_contents =
812      browser()->tab_strip_model()->GetActiveWebContents();
813  GURL expected_without("http://google.com/");
814  EXPECT_EQ(expected_without, web_contents->GetURL());
815
816  PrefService* prefs = browser()->profile()->GetPrefs();
817  EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
818  EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
819
820  // Override the default SafeSearch setting using policies.
821  PolicyMap policies;
822  policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY,
823               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
824  UpdateProviderPolicy(policies);
825
826  EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
827  EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
828
829  content::TestNavigationObserver safesearch_observer(
830      browser()->tab_strip_model()->GetActiveWebContents());
831
832  // Verify that searching from google.com works.
833  chrome::FocusLocationBar(browser());
834  location_bar = browser()->window()->GetLocationBar();
835  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
836  safesearch_observer.Wait();
837  model = location_bar->GetLocationEntry()->model();
838  EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
839  web_contents = browser()->tab_strip_model()->GetActiveWebContents();
840  std::string expected_url("http://google.com/?");
841  expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
842                  chrome::kSafeSearchSsuiParameter;
843  GURL expected_with_parameters(expected_url);
844  EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
845}
846
847IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
848  MakeRequestFail make_request_fail("search.example");
849
850  chrome::EnableInstantExtendedAPIForTesting();
851
852  // Verifies that a default search is made using the provider configured via
853  // policy. Also checks that default search can be completely disabled.
854  const string16 kKeyword(ASCIIToUTF16("testsearch"));
855  const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
856  const std::string kInstantURL("http://does/not/exist");
857  const std::string kAlternateURL0(
858      "https://www.google.com/search#q={searchTerms}");
859  const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
860  const std::string kSearchTermsReplacementKey(
861      "{google:instantExtendedEnabledKey}");
862
863  TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
864      browser()->profile());
865  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
866  TemplateURL* default_search = service->GetDefaultSearchProvider();
867  ASSERT_TRUE(default_search);
868  EXPECT_NE(kKeyword, default_search->keyword());
869  EXPECT_NE(kSearchURL, default_search->url());
870  EXPECT_NE(kInstantURL, default_search->instant_url());
871  EXPECT_FALSE(
872    default_search->alternate_urls().size() == 2 &&
873    default_search->alternate_urls()[0] == kAlternateURL0 &&
874    default_search->alternate_urls()[1] == kAlternateURL1);
875
876  // Override the default search provider using policies.
877  PolicyMap policies;
878  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
879               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
880  policies.Set(key::kDefaultSearchProviderKeyword,
881               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
882               base::Value::CreateStringValue(kKeyword), NULL);
883  policies.Set(key::kDefaultSearchProviderSearchURL,
884               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
885               base::Value::CreateStringValue(kSearchURL), NULL);
886  policies.Set(key::kDefaultSearchProviderInstantURL,
887               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
888               base::Value::CreateStringValue(kInstantURL), NULL);
889  base::ListValue* alternate_urls = new base::ListValue();
890  alternate_urls->AppendString(kAlternateURL0);
891  alternate_urls->AppendString(kAlternateURL1);
892  policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
893               POLICY_SCOPE_USER, alternate_urls, NULL);
894  policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
895               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
896               base::Value::CreateStringValue(kSearchTermsReplacementKey),
897               NULL);
898  UpdateProviderPolicy(policies);
899  default_search = service->GetDefaultSearchProvider();
900  ASSERT_TRUE(default_search);
901  EXPECT_EQ(kKeyword, default_search->keyword());
902  EXPECT_EQ(kSearchURL, default_search->url());
903  EXPECT_EQ(kInstantURL, default_search->instant_url());
904  EXPECT_EQ(2U, default_search->alternate_urls().size());
905  EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
906  EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
907
908  // Query terms replacement requires that the renderer process be a recognized
909  // Instant renderer. Fake it.
910  InstantService* instant_service =
911      InstantServiceFactory::GetForProfile(browser()->profile());
912  instant_service->AddInstantProcess(browser()->tab_strip_model()->
913      GetActiveWebContents()->GetRenderProcessHost()->GetID());
914
915  // Verify that searching from the omnibox does search term replacement with
916  // first URL pattern.
917  chrome::FocusLocationBar(browser());
918  LocationBar* location_bar = browser()->window()->GetLocationBar();
919  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
920      "https://www.google.com/?espv=1#q=foobar");
921  EXPECT_TRUE(
922      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms(false));
923  EXPECT_EQ(ASCIIToUTF16("foobar"),
924            location_bar->GetLocationEntry()->GetText());
925
926  // Verify that not using espv=1 does not do search term replacement.
927  chrome::FocusLocationBar(browser());
928  location_bar = browser()->window()->GetLocationBar();
929  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
930      "https://www.google.com/?q=foobar");
931  EXPECT_FALSE(
932      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms(false));
933  EXPECT_EQ(ASCIIToUTF16("https://www.google.com/?q=foobar"),
934            location_bar->GetLocationEntry()->GetText());
935
936  // Verify that searching from the omnibox does search term replacement with
937  // second URL pattern.
938  chrome::FocusLocationBar(browser());
939  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
940      "https://www.google.com/search?espv=1#q=banana");
941  EXPECT_TRUE(
942      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms(false));
943  EXPECT_EQ(ASCIIToUTF16("banana"),
944            location_bar->GetLocationEntry()->GetText());
945
946  // Verify that searching from the omnibox does search term replacement with
947  // standard search URL pattern.
948  chrome::FocusLocationBar(browser());
949  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
950      "https://www.google.com/search?q=tractor+parts&espv=1");
951  EXPECT_TRUE(
952      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms(false));
953  EXPECT_EQ(ASCIIToUTF16("tractor parts"),
954            location_bar->GetLocationEntry()->GetText());
955
956  // Verify that searching from the omnibox prioritizes hash over query.
957  chrome::FocusLocationBar(browser());
958  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
959      "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
960  EXPECT_TRUE(
961      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms(false));
962  EXPECT_EQ(ASCIIToUTF16("foobar"),
963            location_bar->GetLocationEntry()->GetText());
964}
965
966// The linux and win  bots can't create a GL context. http://crbug.com/103379
967#if defined(OS_MACOSX)
968IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
969  ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
970  // WebGL is enabled by default.
971  content::WebContents* contents =
972      browser()->tab_strip_model()->GetActiveWebContents();
973  EXPECT_TRUE(IsWebGLEnabled(contents));
974  // Disable with a policy.
975  PolicyMap policies;
976  policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
977               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
978  UpdateProviderPolicy(policies);
979  // Crash and reload the tab to get a new renderer.
980  content::CrashTab(contents);
981  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
982  EXPECT_FALSE(IsWebGLEnabled(contents));
983  // Enable with a policy.
984  policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
985               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
986  UpdateProviderPolicy(policies);
987  content::CrashTab(contents);
988  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
989  EXPECT_TRUE(IsWebGLEnabled(contents));
990}
991#endif
992
993IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
994  // Verifies that SPDY can be disable by policy.
995  EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
996  PolicyMap policies;
997  policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
998               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
999  UpdateProviderPolicy(policies);
1000  content::RunAllPendingInMessageLoop();
1001  EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1002  // Verify that it can be force-enabled too.
1003  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1004  policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1005               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1006  UpdateProviderPolicy(policies);
1007  content::RunAllPendingInMessageLoop();
1008  EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1009}
1010
1011IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1012  // Verifies that plugins can be forced to be disabled by policy.
1013
1014  // Verify that the Flash plugin exists and that it can be enabled and disabled
1015  // by the user.
1016  std::vector<content::WebPluginInfo> plugins;
1017  GetPluginList(&plugins);
1018  const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1019  if (!flash)
1020    return;
1021  PluginPrefs* plugin_prefs =
1022      PluginPrefs::GetForProfile(browser()->profile()).get();
1023  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1024  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1025  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1026  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1027  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1028
1029  // Now disable it with a policy.
1030  base::ListValue disabled_plugins;
1031  disabled_plugins.Append(base::Value::CreateStringValue("*Flash*"));
1032  PolicyMap policies;
1033  policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1034               POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1035  UpdateProviderPolicy(policies);
1036  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1037  // The user shouldn't be able to enable it.
1038  EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1039  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1040}
1041
1042IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1043  // Verifies that plugins with an exception in the blacklist can be enabled.
1044
1045  // Verify that the Flash plugin exists and that it can be enabled and disabled
1046  // by the user.
1047  std::vector<content::WebPluginInfo> plugins;
1048  GetPluginList(&plugins);
1049  const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1050  if (!flash)
1051    return;
1052  PluginPrefs* plugin_prefs =
1053      PluginPrefs::GetForProfile(browser()->profile()).get();
1054  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1055
1056  // Disable all plugins.
1057  base::ListValue disabled_plugins;
1058  disabled_plugins.Append(base::Value::CreateStringValue("*"));
1059  PolicyMap policies;
1060  policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1061               POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1062  UpdateProviderPolicy(policies);
1063  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1064  // The user shouldn't be able to enable it.
1065  EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1066  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1067
1068  // Now open an exception for flash.
1069  base::ListValue disabled_plugins_exceptions;
1070  disabled_plugins_exceptions.Append(
1071      base::Value::CreateStringValue("*Flash*"));
1072  policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1073               POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1074  UpdateProviderPolicy(policies);
1075  // It should revert to the user's preference automatically.
1076  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1077  // And the user should be able to disable and enable again.
1078  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1079  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1080  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1081  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1082}
1083
1084IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1085  // Verifies that a plugin can be force-installed with a policy.
1086  std::vector<content::WebPluginInfo> plugins;
1087  GetPluginList(&plugins);
1088  const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1089  if (!flash)
1090    return;
1091  PluginPrefs* plugin_prefs =
1092      PluginPrefs::GetForProfile(browser()->profile()).get();
1093  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1094
1095  // The user disables it and then a policy forces it to be enabled.
1096  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1097  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1098  base::ListValue plugin_list;
1099  plugin_list.Append(base::Value::CreateStringValue(kFlashPluginName));
1100  PolicyMap policies;
1101  policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1102               POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1103  UpdateProviderPolicy(policies);
1104  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1105  // The user can't disable it anymore.
1106  EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1107  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1108
1109  // When a plugin is both enabled and disabled, the whitelist takes precedence.
1110  policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1111               POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1112  UpdateProviderPolicy(policies);
1113  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1114}
1115
1116IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1117  // Verifies that dangerous plugins can be always authorized to run with
1118  // a policy.
1119
1120  // Verify that the test page exists. It is only present in checkouts with
1121  // src-internal.
1122  if (!base::PathExists(ui_test_utils::GetTestFilePath(
1123      base::FilePath(FILE_PATH_LITERAL("plugin")),
1124      base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1125    LOG(INFO) <<
1126        "Test skipped because plugin/quicktime.html test file wasn't found.";
1127    return;
1128  }
1129
1130  ServeContentTestData();
1131  // No plugins at startup.
1132  EXPECT_EQ(0, CountPlugins());
1133
1134  content::WebContents* contents =
1135      browser()->tab_strip_model()->GetActiveWebContents();
1136  ASSERT_TRUE(contents);
1137  InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1138  ASSERT_TRUE(infobar_service);
1139  EXPECT_EQ(0u, infobar_service->infobar_count());
1140
1141  base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1142  GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1143  ui_test_utils::NavigateToURL(browser(), url);
1144  // This should have triggered the dangerous plugin infobar.
1145  ASSERT_EQ(1u, infobar_service->infobar_count());
1146  EXPECT_TRUE(infobar_service->infobar_at(0)->AsConfirmInfoBarDelegate());
1147  // And the plugin isn't running.
1148  EXPECT_EQ(0, CountPlugins());
1149
1150  // Now set a policy to always authorize this.
1151  PolicyMap policies;
1152  policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY,
1153               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1154  UpdateProviderPolicy(policies);
1155  // Reloading the page shouldn't trigger the infobar this time.
1156  ui_test_utils::NavigateToURL(browser(), url);
1157  EXPECT_EQ(0u, infobar_service->infobar_count());
1158  // And the plugin started automatically.
1159  EXPECT_EQ(1, CountPlugins());
1160}
1161
1162IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1163  // Verifies that access to the developer tools can be disabled.
1164
1165  // Open devtools.
1166  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1167  content::WebContents* contents =
1168      browser()->tab_strip_model()->GetActiveWebContents();
1169  EXPECT_TRUE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents));
1170
1171  // Disable devtools via policy.
1172  PolicyMap policies;
1173  policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1174               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1175  UpdateProviderPolicy(policies);
1176  // The existing devtools window should have closed.
1177  EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents));
1178  // And it's not possible to open it again.
1179  EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1180  EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents));
1181}
1182
1183IN_PROC_BROWSER_TEST_F(PolicyTest, WebStoreIconHidden) {
1184#if defined(OS_WIN) && defined(USE_ASH)
1185  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1186  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1187    return;
1188#endif
1189
1190  // Verifies that the web store icons can be hidden from the new tab page.
1191
1192  // Open new tab page and look for the web store icons.
1193  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1194  content::WebContents* contents =
1195    browser()->tab_strip_model()->GetActiveWebContents();
1196
1197#if !defined(OS_CHROMEOS)
1198  // Look for web store's app ID in the apps page.
1199  EXPECT_TRUE(ContainsVisibleElement(contents,
1200                                     "ahfgeienlihckogmohjhadlkjgocpleb"));
1201#endif
1202
1203  // The next NTP has no footer.
1204  if (ContainsVisibleElement(contents, "footer"))
1205    EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1206
1207  // Turn off the web store icons.
1208  PolicyMap policies;
1209  policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
1210               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1211  UpdateProviderPolicy(policies);
1212
1213  // The web store icons should now be hidden.
1214  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1215  EXPECT_FALSE(ContainsVisibleElement(contents,
1216                                      "ahfgeienlihckogmohjhadlkjgocpleb"));
1217  EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1218}
1219
1220// This policy isn't available on Chrome OS.
1221#if !defined(OS_CHROMEOS)
1222IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1223  // Verifies that the download directory can be forced by policy.
1224
1225  // Set the initial download directory.
1226  base::ScopedTempDir initial_dir;
1227  ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1228  browser()->profile()->GetPrefs()->SetFilePath(
1229      prefs::kDownloadDefaultDirectory, initial_dir.path());
1230  // Don't prompt for the download location during this test.
1231  browser()->profile()->GetPrefs()->SetBoolean(
1232      prefs::kPromptForDownload, false);
1233
1234  // Verify that downloads end up on the default directory.
1235  base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1236  DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1237  file_util::DieFileDie(initial_dir.path().Append(file), false);
1238
1239  // Override the download directory with the policy and verify a download.
1240  base::ScopedTempDir forced_dir;
1241  ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1242  PolicyMap policies;
1243  policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
1244               POLICY_SCOPE_USER,
1245               base::Value::CreateStringValue(forced_dir.path().value()), NULL);
1246  UpdateProviderPolicy(policies);
1247  DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1248  // Verify that the first download location wasn't affected.
1249  EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1250}
1251#endif
1252
1253// There's a bug filed for flakiness on windows: http://crbug.com/248464.
1254// Unfortunately, the bug doesn't contain any actionable information, so this
1255// test is temporarily marked FLAKY to get some cycles on the builders in order
1256// to gather data on the nature of the flakes.
1257// TODO(mnissler): Flip back to DISABLED after obtaining logs from flaky runs.
1258#if defined(OS_WIN)
1259#define MAYBE_ExtensionInstallBlacklist FLAKY_ExtensionInstallBlacklist
1260#else
1261#define MAYBE_ExtensionInstallBlacklist ExtensionInstallBlacklist
1262#endif
1263
1264IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklist) {
1265  // Verifies that blacklisted extensions can't be installed.
1266  ExtensionService* service = extension_service();
1267  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1268  ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1269  base::ListValue blacklist;
1270  blacklist.Append(base::Value::CreateStringValue(kGoodCrxId));
1271  PolicyMap policies;
1272  policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1273               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1274  UpdateProviderPolicy(policies);
1275
1276  // "good.crx" is blacklisted.
1277  EXPECT_FALSE(InstallExtension(kGoodCrxName));
1278  EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1279
1280  // "adblock.crx" is not.
1281  const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1282  ASSERT_TRUE(adblock);
1283  EXPECT_EQ(kAdBlockCrxId, adblock->id());
1284  EXPECT_EQ(adblock,
1285            service->GetExtensionById(kAdBlockCrxId, true));
1286
1287  // Now blacklist all extensions.
1288  blacklist.Clear();
1289  blacklist.Append(base::Value::CreateStringValue("*"));
1290  policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1291               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1292  UpdateProviderPolicy(policies);
1293  // AdBlock was automatically removed.
1294  ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1295  // And can't be installed again, nor can good.crx.
1296  EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1297  EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1298  EXPECT_FALSE(InstallExtension(kGoodCrxName));
1299  EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1300}
1301
1302IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1303  // Verifies that the whitelist can open exceptions to the blacklist.
1304  ExtensionService* service = extension_service();
1305  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1306  ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1307  base::ListValue blacklist;
1308  blacklist.Append(base::Value::CreateStringValue("*"));
1309  base::ListValue whitelist;
1310  whitelist.Append(base::Value::CreateStringValue(kGoodCrxId));
1311  PolicyMap policies;
1312  policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1313               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1314  policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1315               POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1316  UpdateProviderPolicy(policies);
1317  // "adblock.crx" is blacklisted.
1318  EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1319  EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1320  // "good.crx" has a whitelist exception.
1321  const extensions::Extension* good = InstallExtension(kGoodCrxName);
1322  ASSERT_TRUE(good);
1323  EXPECT_EQ(kGoodCrxId, good->id());
1324  EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1325  // The user can also remove this extension.
1326  UninstallExtension(kGoodCrxId, true);
1327}
1328
1329IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1330  // Verifies that extensions that are force-installed by policies are
1331  // installed and can't be uninstalled.
1332  ExtensionService* service = extension_service();
1333  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1334
1335  // Extensions that are force-installed come from an update URL, which defaults
1336  // to the webstore. Use a mock URL for this test with an update manifest
1337  // that includes "good_v1.crx".
1338  base::FilePath path =
1339      base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1340  GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1341
1342  // Setting the forcelist extension should install "good_v1.crx".
1343  base::ListValue forcelist;
1344  forcelist.Append(base::Value::CreateStringValue(base::StringPrintf(
1345      "%s;%s", kGoodCrxId, url.spec().c_str())));
1346  PolicyMap policies;
1347  policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1348               POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1349  content::WindowedNotificationObserver observer(
1350      chrome::NOTIFICATION_EXTENSION_INSTALLED,
1351      content::NotificationService::AllSources());
1352  UpdateProviderPolicy(policies);
1353  observer.Wait();
1354  // Note: Cannot check that the notification details match the expected
1355  // exception, since the details object has already been freed prior to
1356  // the completion of observer.Wait().
1357
1358  EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1359
1360  // The user is not allowed to uninstall force-installed extensions.
1361  UninstallExtension(kGoodCrxId, false);
1362
1363  // The user is not allowed to load an unpacked extension with the
1364  // same ID as a force-installed extension.
1365  LoadUnpackedExtension(kGoodUnpackedExt, false);
1366
1367  // Loading other unpacked extensions are not blocked.
1368  LoadUnpackedExtension(kAppUnpackedExt, true);
1369
1370  const std::string old_version_number =
1371      service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1372
1373  base::FilePath test_path;
1374  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1375
1376  TestRequestInterceptor interceptor("update.extension");
1377  interceptor.PushJobCallback(
1378      TestRequestInterceptor::FileJob(
1379          test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1380
1381  // Updating the force-installed extension.
1382  extensions::ExtensionUpdater* updater = service->updater();
1383  extensions::ExtensionUpdater::CheckParams params;
1384  params.install_immediately = true;
1385  content::WindowedNotificationObserver update_observer(
1386      chrome::NOTIFICATION_EXTENSION_INSTALLED,
1387      content::NotificationService::AllSources());
1388  updater->CheckNow(params);
1389  update_observer.Wait();
1390
1391  const base::Version* new_version =
1392      service->GetExtensionById(kGoodCrxId, true)->version();
1393  ASSERT_TRUE(new_version->IsValid());
1394  base::Version old_version(old_version_number);
1395  ASSERT_TRUE(old_version.IsValid());
1396
1397  EXPECT_EQ(1, new_version->CompareTo(old_version));
1398
1399  EXPECT_EQ(0u, interceptor.GetPendingSize());
1400}
1401
1402IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1403  // Verifies that extensions are blocked if policy specifies an allowed types
1404  // list and the extension's type is not on that list.
1405  ExtensionService* service = extension_service();
1406  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1407  ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1408
1409  base::ListValue allowed_types;
1410  allowed_types.AppendString("hosted_app");
1411  PolicyMap policies;
1412  policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1413               POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1414  UpdateProviderPolicy(policies);
1415
1416  // "good.crx" is blocked.
1417  EXPECT_FALSE(InstallExtension(kGoodCrxName));
1418  EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1419
1420  // "hosted_app.crx" is of a whitelisted type.
1421  const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1422  ASSERT_TRUE(hosted_app);
1423  EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1424  EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1425
1426  // The user can remove the extension.
1427  UninstallExtension(kHostedAppCrxId, true);
1428}
1429
1430// Checks that a click on an extension CRX download triggers the extension
1431// installation prompt without further user interaction when the source is
1432// whitelisted by policy.
1433IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallSources) {
1434  CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1435      switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
1436
1437  const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1438      base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1439  const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1440      base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1441
1442  const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1443      FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1444  ui_test_utils::NavigateToURL(browser(), download_page_url);
1445
1446  // As long as the policy is not present, extensions are considered dangerous.
1447  content::DownloadTestObserverTerminal download_observer(
1448      content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1449      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1450  PerformClick(0, 0);
1451  download_observer.WaitForFinished();
1452
1453  // Install the policy and trigger another download.
1454  base::ListValue install_sources;
1455  install_sources.AppendString(install_source_url.spec());
1456  install_sources.AppendString(referrer_url.spec());
1457  PolicyMap policies;
1458  policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1459               POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1460  UpdateProviderPolicy(policies);
1461
1462  content::WindowedNotificationObserver observer(
1463      chrome::NOTIFICATION_EXTENSION_INSTALLED,
1464      content::NotificationService::AllSources());
1465  PerformClick(1, 0);
1466  observer.Wait();
1467  // Note: Cannot check that the notification details match the expected
1468  // exception, since the details object has already been freed prior to
1469  // the completion of observer.Wait().
1470
1471  // The first extension shouldn't be present, the second should be there.
1472  EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1473  EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1474}
1475
1476IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1477#if defined(OS_WIN) && defined(USE_ASH)
1478  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1479  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1480    return;
1481#endif
1482
1483  // Verifies that the homepage can be configured with policies.
1484  // Set a default, and check that the home button navigates there.
1485  browser()->profile()->GetPrefs()->SetString(
1486      prefs::kHomePage, chrome::kChromeUIPolicyURL);
1487  browser()->profile()->GetPrefs()->SetBoolean(
1488      prefs::kHomePageIsNewTabPage, false);
1489  EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1490            browser()->profile()->GetHomePage());
1491  content::WebContents* contents =
1492      browser()->tab_strip_model()->GetActiveWebContents();
1493  EXPECT_EQ(GURL(content::kAboutBlankURL), contents->GetURL());
1494  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1495  EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1496
1497  // Now override with policy.
1498  PolicyMap policies;
1499  policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
1500               POLICY_SCOPE_USER,
1501               base::Value::CreateStringValue(chrome::kChromeUICreditsURL),
1502               NULL);
1503  UpdateProviderPolicy(policies);
1504  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1505  content::WaitForLoadStop(contents);
1506  EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1507
1508  policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
1509               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1510  UpdateProviderPolicy(policies);
1511  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1512  content::WaitForLoadStop(contents);
1513  EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1514}
1515
1516IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1517  // Verifies that incognito windows can't be opened when disabled by policy.
1518
1519  const BrowserList* active_browser_list =
1520      BrowserList::GetInstance(chrome::GetActiveDesktop());
1521
1522  // Disable incognito via policy and verify that incognito windows can't be
1523  // opened.
1524  EXPECT_EQ(1u, active_browser_list->size());
1525  EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1526  PolicyMap policies;
1527  policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1528               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1529  UpdateProviderPolicy(policies);
1530  EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1531  EXPECT_EQ(1u, active_browser_list->size());
1532  EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1533
1534  // Enable via policy and verify that incognito windows can be opened.
1535  policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1536               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1537  UpdateProviderPolicy(policies);
1538  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1539  EXPECT_EQ(2u, active_browser_list->size());
1540  EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1541}
1542
1543IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1544  // Verifies that Javascript can be disabled.
1545  content::WebContents* contents =
1546      browser()->tab_strip_model()->GetActiveWebContents();
1547  EXPECT_TRUE(IsJavascriptEnabled(contents));
1548  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1549  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1550
1551  // Disable Javascript via policy.
1552  PolicyMap policies;
1553  policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
1554               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1555  UpdateProviderPolicy(policies);
1556  // Reload the page.
1557  ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1558  EXPECT_FALSE(IsJavascriptEnabled(contents));
1559  // Developer tools still work when javascript is disabled.
1560  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1561  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1562  // Javascript is always enabled for the internal pages.
1563  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1564  EXPECT_TRUE(IsJavascriptEnabled(contents));
1565
1566  // The javascript content setting policy overrides the javascript policy.
1567  ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1568  EXPECT_FALSE(IsJavascriptEnabled(contents));
1569  policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
1570               POLICY_SCOPE_USER,
1571               base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW), NULL);
1572  UpdateProviderPolicy(policies);
1573  ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1574  EXPECT_TRUE(IsJavascriptEnabled(contents));
1575}
1576
1577IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
1578  // Verifies that browsing history is not saved.
1579  PolicyMap policies;
1580  policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1581               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1582  UpdateProviderPolicy(policies);
1583  GURL url = ui_test_utils::GetTestUrl(
1584      base::FilePath(base::FilePath::kCurrentDirectory),
1585      base::FilePath(FILE_PATH_LITERAL("empty.html")));
1586  ui_test_utils::NavigateToURL(browser(), url);
1587  // Verify that the navigation wasn't saved in the history.
1588  ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
1589  EXPECT_EQ(0u, enumerator1.urls().size());
1590
1591  // Now flip the policy and try again.
1592  policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1593               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1594  UpdateProviderPolicy(policies);
1595  ui_test_utils::NavigateToURL(browser(), url);
1596  // Verify that the navigation was saved in the history.
1597  ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
1598  ASSERT_EQ(1u, enumerator2.urls().size());
1599  EXPECT_EQ(url, enumerator2.urls()[0]);
1600}
1601
1602// http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
1603IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
1604  // Verifies that translate can be forced enabled or disabled by policy.
1605
1606  // Get the InfoBarService, and verify that there are no infobars on startup.
1607  content::WebContents* contents =
1608      browser()->tab_strip_model()->GetActiveWebContents();
1609  ASSERT_TRUE(contents);
1610  InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1611  ASSERT_TRUE(infobar_service);
1612  EXPECT_EQ(0u, infobar_service->infobar_count());
1613
1614  // Force enable the translate feature.
1615  PolicyMap policies;
1616  policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1617               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1618  UpdateProviderPolicy(policies);
1619  // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
1620  // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
1621  // TranslateManager observes. This allows checking that an infobar is NOT
1622  // shown below, without polling for infobars for some indeterminate amount
1623  // of time.
1624  GURL url = ui_test_utils::GetTestUrl(
1625      base::FilePath(),
1626      base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
1627  content::WindowedNotificationObserver language_observer1(
1628      chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1629      content::NotificationService::AllSources());
1630  ui_test_utils::NavigateToURL(browser(), url);
1631  language_observer1.Wait();
1632
1633  // Verify the translation detected for this tab.
1634  TranslateTabHelper* translate_tab_helper =
1635      TranslateTabHelper::FromWebContents(contents);
1636  ASSERT_TRUE(translate_tab_helper);
1637  LanguageState& language_state = translate_tab_helper->language_state();
1638  EXPECT_EQ("fr", language_state.original_language());
1639  EXPECT_TRUE(language_state.page_needs_translation());
1640  EXPECT_FALSE(language_state.translation_pending());
1641  EXPECT_FALSE(language_state.translation_declined());
1642  EXPECT_FALSE(language_state.IsPageTranslated());
1643
1644  // Verify that the translate infobar showed up.
1645  ASSERT_EQ(1u, infobar_service->infobar_count());
1646  InfoBarDelegate* infobar = infobar_service->infobar_at(0);
1647  TranslateInfoBarDelegate* translate_infobar_delegate =
1648      infobar->AsTranslateInfoBarDelegate();
1649  ASSERT_TRUE(translate_infobar_delegate);
1650  EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE,
1651            translate_infobar_delegate->infobar_type());
1652  EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
1653
1654  // Now force disable translate.
1655  infobar_service->RemoveInfoBar(infobar);
1656  EXPECT_EQ(0u, infobar_service->infobar_count());
1657  policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1658               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1659  UpdateProviderPolicy(policies);
1660  // Navigating to the same URL now doesn't trigger an infobar.
1661  content::WindowedNotificationObserver language_observer2(
1662      chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1663      content::NotificationService::AllSources());
1664  ui_test_utils::NavigateToURL(browser(), url);
1665  language_observer2.Wait();
1666  EXPECT_EQ(0u, infobar_service->infobar_count());
1667}
1668
1669IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
1670  // Checks that URLs can be blacklisted, and that exceptions can be made to
1671  // the blacklist.
1672
1673  // Filter |kURLS| on IO thread, so that requests to those hosts end up
1674  // as URLRequestMockHTTPJobs.
1675  const char* kURLS[] = {
1676    "http://aaa.com/empty.html",
1677    "http://bbb.com/empty.html",
1678    "http://sub.bbb.com/empty.html",
1679    "http://bbb.com/policy/blank.html",
1680  };
1681  {
1682    base::RunLoop loop;
1683    BrowserThread::PostTaskAndReply(
1684        BrowserThread::IO, FROM_HERE,
1685        base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
1686        loop.QuitClosure());
1687    loop.Run();
1688  }
1689
1690  // Verify that "bbb.com" opens before applying the blacklist.
1691  CheckCanOpenURL(browser(), kURLS[1]);
1692
1693  // Set a blacklist.
1694  base::ListValue blacklist;
1695  blacklist.Append(base::Value::CreateStringValue("bbb.com"));
1696  PolicyMap policies;
1697  policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1698               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1699  UpdateProviderPolicy(policies);
1700  FlushBlacklistPolicy();
1701  // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
1702  CheckCanOpenURL(browser(), kURLS[0]);
1703  for (size_t i = 1; i < arraysize(kURLS); ++i)
1704    CheckURLIsBlocked(browser(), kURLS[i]);
1705
1706  // Whitelist some sites of bbb.com.
1707  base::ListValue whitelist;
1708  whitelist.Append(base::Value::CreateStringValue("sub.bbb.com"));
1709  whitelist.Append(base::Value::CreateStringValue("bbb.com/policy"));
1710  policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
1711               POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1712  UpdateProviderPolicy(policies);
1713  FlushBlacklistPolicy();
1714  CheckURLIsBlocked(browser(), kURLS[1]);
1715  CheckCanOpenURL(browser(), kURLS[2]);
1716  CheckCanOpenURL(browser(), kURLS[3]);
1717
1718  {
1719    base::RunLoop loop;
1720    BrowserThread::PostTaskAndReply(
1721        BrowserThread::IO, FROM_HERE,
1722        base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
1723        loop.QuitClosure());
1724    loop.Run();
1725  }
1726}
1727
1728IN_PROC_BROWSER_TEST_F(PolicyTest, FileURLBlacklist) {
1729  // Check that FileURLs can be blacklisted and DisabledSchemes works together
1730  // with URLblacklisting and URLwhitelisting.
1731
1732  base::FilePath test_path;
1733  PathService::Get(chrome::DIR_TEST_DATA, &test_path);
1734  const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
1735  const std::string folder_path = base_path + "apptest/";
1736  const std::string file_path1 = base_path + "title1.html";
1737  const std::string file_path2 = folder_path + "basic.html";
1738
1739  CheckCanOpenURL(browser(), file_path1.c_str());
1740  CheckCanOpenURL(browser(), file_path2.c_str());
1741
1742  // Set a blacklist for all the files.
1743  base::ListValue blacklist;
1744  blacklist.Append(base::Value::CreateStringValue("file://*"));
1745  PolicyMap policies;
1746  policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1747               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1748  UpdateProviderPolicy(policies);
1749  FlushBlacklistPolicy();
1750
1751  CheckURLIsBlocked(browser(), file_path1.c_str());
1752  CheckURLIsBlocked(browser(), file_path2.c_str());
1753
1754  // Replace the URLblacklist with disabling the file scheme.
1755  blacklist.Remove(base::StringValue("file://*"), NULL);
1756  policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1757               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1758  UpdateProviderPolicy(policies);
1759  FlushBlacklistPolicy();
1760
1761  PrefService* prefs = browser()->profile()->GetPrefs();
1762  const base::ListValue* list_url = prefs->GetList(prefs::kUrlBlacklist);
1763  EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
1764            list_url->end());
1765
1766  base::ListValue disabledscheme;
1767  disabledscheme.Append(base::Value::CreateStringValue("file"));
1768  policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
1769               POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
1770  UpdateProviderPolicy(policies);
1771  FlushBlacklistPolicy();
1772
1773  list_url = prefs->GetList(prefs::kUrlBlacklist);
1774  EXPECT_NE(list_url->Find(base::StringValue("file://*")),
1775            list_url->end());
1776
1777  // Whitelist one folder and blacklist an another just inside.
1778  base::ListValue whitelist;
1779  whitelist.Append(base::Value::CreateStringValue(base_path));
1780  policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
1781               POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1782  blacklist.Append(base::Value::CreateStringValue(folder_path));
1783  policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1784               POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1785  UpdateProviderPolicy(policies);
1786  FlushBlacklistPolicy();
1787
1788  CheckCanOpenURL(browser(), file_path1.c_str());
1789  CheckURLIsBlocked(browser(), file_path2.c_str());
1790}
1791
1792#if defined(OS_CHROMEOS)
1793IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
1794  int screenshot_count = CountScreenshots();
1795
1796  // Make sure screenshots are counted correctly.
1797  TestScreenshotFile(true);
1798  ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
1799
1800  // Check if trying to take a screenshot fails when disabled by policy.
1801  TestScreenshotFile(false);
1802  ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
1803}
1804
1805IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
1806  // Set up the mock observer.
1807  chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
1808  scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
1809  audio_handler->AddAudioObserver(test_observer.get());
1810
1811  bool prior_state = audio_handler->IsOutputMuted();
1812  // Make sure the audio is not muted and then toggle the policy and observe
1813  // if the output mute changed event is fired.
1814  audio_handler->SetOutputMute(false);
1815  EXPECT_FALSE(audio_handler->IsOutputMuted());
1816  EXPECT_EQ(1, test_observer->output_mute_changed_count());
1817  PolicyMap policies;
1818  policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
1819               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1820  UpdateProviderPolicy(policies);
1821  EXPECT_TRUE(audio_handler->IsOutputMuted());
1822  // This should not change the state now and should not trigger output mute
1823  // changed event.
1824  audio_handler->SetOutputMute(false);
1825  EXPECT_TRUE(audio_handler->IsOutputMuted());
1826  EXPECT_EQ(1, test_observer->output_mute_changed_count());
1827
1828  // Toggle back and observe if the output mute changed event is fired.
1829  policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
1830               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1831  UpdateProviderPolicy(policies);
1832  EXPECT_FALSE(audio_handler->IsOutputMuted());
1833  EXPECT_EQ(1, test_observer->output_mute_changed_count());
1834  audio_handler->SetOutputMute(true);
1835  EXPECT_TRUE(audio_handler->IsOutputMuted());
1836  EXPECT_EQ(2, test_observer->output_mute_changed_count());
1837  // Revert the prior state.
1838  audio_handler->SetOutputMute(prior_state);
1839  audio_handler->RemoveAudioObserver(test_observer.get());
1840}
1841
1842IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_SessionLengthLimit) {
1843  // Set the session start time to 2 hours ago.
1844  g_browser_process->local_state()->SetInt64(
1845      prefs::kSessionStartTime,
1846      (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
1847          .ToInternalValue());
1848}
1849
1850IN_PROC_BROWSER_TEST_F(PolicyTest, SessionLengthLimit) {
1851  content::MockNotificationObserver observer;
1852  content::NotificationRegistrar registrar;
1853  registrar.Add(&observer,
1854                chrome::NOTIFICATION_APP_TERMINATING,
1855                content::NotificationService::AllSources());
1856
1857  // Set the session length limit to 3 hours. Verify that the session is not
1858  // terminated.
1859  EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
1860      .Times(0);
1861  PolicyMap policies;
1862  policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
1863               POLICY_SCOPE_USER,
1864               base::Value::CreateIntegerValue(180 * 60 * 1000),  // 3 hours.
1865               NULL);
1866  UpdateProviderPolicy(policies);
1867  base::RunLoop().RunUntilIdle();
1868  Mock::VerifyAndClearExpectations(&observer);
1869
1870  // Decrease the session length limit to 1 hour. Verify that the session is
1871  // terminated immediately.
1872  EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
1873  policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
1874               POLICY_SCOPE_USER,
1875               base::Value::CreateIntegerValue(60 * 60 * 1000),  // 1 hour.
1876               NULL);
1877  UpdateProviderPolicy(policies);
1878  base::RunLoop().RunUntilIdle();
1879  Mock::VerifyAndClearExpectations(&observer);
1880}
1881
1882IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
1883  // Verifies that the large cursor accessibility feature can be controlled
1884  // through policy.
1885  chromeos::AccessibilityManager* accessibility_manager =
1886      chromeos::AccessibilityManager::Get();
1887
1888  // Manually enable the large cursor.
1889  accessibility_manager->EnableLargeCursor(true);
1890  EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
1891
1892  // Verify that policy overrides the manual setting.
1893  PolicyMap policies;
1894  policies.Set(key::kLargeCursorEnabled, POLICY_LEVEL_MANDATORY,
1895               POLICY_SCOPE_USER,
1896               base::Value::CreateBooleanValue(false), NULL);
1897  UpdateProviderPolicy(policies);
1898  EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
1899
1900  // Verify that the large cursor cannot be enabled manually anymore.
1901  accessibility_manager->EnableLargeCursor(true);
1902  EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
1903}
1904
1905IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
1906  // Verifies that the spoken feedback accessibility feature can be controlled
1907  // through policy.
1908  chromeos::AccessibilityManager* accessibility_manager =
1909      chromeos::AccessibilityManager::Get();
1910
1911  // Manually enable spoken feedback.
1912  accessibility_manager->EnableSpokenFeedback(
1913      true, ash::A11Y_NOTIFICATION_NONE);
1914  EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
1915
1916  // Verify that policy overrides the manual setting.
1917  PolicyMap policies;
1918  policies.Set(key::kSpokenFeedbackEnabled, POLICY_LEVEL_MANDATORY,
1919               POLICY_SCOPE_USER,
1920               base::Value::CreateBooleanValue(false), NULL);
1921  UpdateProviderPolicy(policies);
1922  EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
1923
1924  // Verify that spoken feedback cannot be enabled manually anymore.
1925  accessibility_manager->EnableSpokenFeedback(
1926      true, ash::A11Y_NOTIFICATION_NONE);
1927  EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
1928}
1929
1930IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
1931  // Verifies that the high contrast mode accessibility feature can be
1932  // controlled through policy.
1933  chromeos::AccessibilityManager* accessibility_manager =
1934      chromeos::AccessibilityManager::Get();
1935
1936  // Manually enable high contrast mode.
1937  accessibility_manager->EnableHighContrast(true);
1938  EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
1939
1940  // Verify that policy overrides the manual setting.
1941  PolicyMap policies;
1942  policies.Set(key::kHighContrastEnabled, POLICY_LEVEL_MANDATORY,
1943               POLICY_SCOPE_USER,
1944               base::Value::CreateBooleanValue(false), NULL);
1945  UpdateProviderPolicy(policies);
1946  EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
1947
1948  // Verify that high contrast mode cannot be enabled manually anymore.
1949  accessibility_manager->EnableHighContrast(true);
1950  EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
1951}
1952
1953IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
1954  // Verifies that the screen magnifier can be disabled through policy.
1955  chromeos::MagnificationManager* magnification_manager =
1956      chromeos::MagnificationManager::Get();
1957
1958  // Manually enable the full-screen magnifier.
1959  magnification_manager->SetMagnifierType(ash::MAGNIFIER_FULL);
1960  magnification_manager->SetMagnifierEnabled(true);
1961  EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
1962  EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
1963
1964  // Verify that policy overrides the manual setting.
1965  PolicyMap policies;
1966  policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
1967               POLICY_SCOPE_USER,
1968               base::Value::CreateIntegerValue(0), NULL);
1969  UpdateProviderPolicy(policies);
1970  EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
1971
1972  // Verify that the screen magnifier cannot be enabled manually anymore.
1973  magnification_manager->SetMagnifierEnabled(true);
1974  EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
1975}
1976
1977IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
1978  // Verifies that the full-screen magnifier can be enabled through policy.
1979  chromeos::MagnificationManager* magnification_manager =
1980      chromeos::MagnificationManager::Get();
1981
1982  // Verify that the screen magnifier is initially disabled.
1983  EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
1984
1985  // Verify that policy can enable the full-screen magnifier.
1986  PolicyMap policies;
1987  policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
1988               POLICY_SCOPE_USER,
1989               base::Value::CreateIntegerValue(ash::MAGNIFIER_FULL), NULL);
1990  UpdateProviderPolicy(policies);
1991  EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
1992  EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
1993
1994  // Verify that the screen magnifier cannot be disabled manually anymore.
1995  magnification_manager->SetMagnifierEnabled(false);
1996  EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
1997}
1998
1999#endif
2000
2001namespace {
2002
2003static const char* kRestoredURLs[] = {
2004  "http://aaa.com/empty.html",
2005  "http://bbb.com/empty.html",
2006};
2007
2008bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2009  return s.empty() || s[0] != '-';
2010}
2011
2012}  // namespace
2013
2014// Similar to PolicyTest but allows setting policies before the browser is
2015// created. Each test parameter is a method that sets up the early policies
2016// and stores the expected startup URLs in |expected_urls_|.
2017class RestoreOnStartupPolicyTest
2018    : public PolicyTest,
2019      public testing::WithParamInterface<
2020          void (RestoreOnStartupPolicyTest::*)(void)> {
2021 public:
2022  RestoreOnStartupPolicyTest() {}
2023  virtual ~RestoreOnStartupPolicyTest() {}
2024
2025#if defined(OS_CHROMEOS)
2026  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2027    // TODO(nkostylev): Investigate if we can remove this switch.
2028    command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2029    PolicyTest::SetUpCommandLine(command_line);
2030  }
2031#endif
2032
2033  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2034    PolicyTest::SetUpInProcessBrowserTestFixture();
2035    // Set early policies now, before the browser is created.
2036    (this->*(GetParam()))();
2037
2038    // Remove the non-switch arguments, so that session restore kicks in for
2039    // these tests.
2040    CommandLine* command_line = CommandLine::ForCurrentProcess();
2041    CommandLine::StringVector argv = command_line->argv();
2042    argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2043               argv.end());
2044    command_line->InitFromArgv(argv);
2045    ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2046                           command_line->argv().begin()));
2047
2048    // Redirect the test URLs to the test data directory.
2049    RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs));
2050  }
2051
2052  void HomepageIsNotNTP() {
2053    // Verifies that policy can set the startup pages to the homepage, when
2054    // the homepage is not the NTP.
2055    PolicyMap policies;
2056    policies.Set(
2057        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2058        base::Value::CreateIntegerValue(
2059            SessionStartupPref::kPrefValueHomePage),
2060        NULL);
2061    policies.Set(
2062        key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2063        base::Value::CreateBooleanValue(false), NULL);
2064    policies.Set(
2065        key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2066        base::Value::CreateStringValue(kRestoredURLs[1]), NULL);
2067    provider_.UpdateChromePolicy(policies);
2068
2069    expected_urls_.push_back(GURL(kRestoredURLs[1]));
2070  }
2071
2072  void HomepageIsNTP() {
2073    // Verifies that policy can set the startup pages to the homepage, when
2074    // the homepage is the NTP.
2075    PolicyMap policies;
2076    policies.Set(
2077        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2078        base::Value::CreateIntegerValue(
2079            SessionStartupPref::kPrefValueHomePage),
2080        NULL);
2081    policies.Set(
2082        key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2083        base::Value::CreateBooleanValue(true), NULL);
2084    provider_.UpdateChromePolicy(policies);
2085
2086    expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2087  }
2088
2089  void ListOfURLs() {
2090    // Verifies that policy can set the startup pages to a list of URLs.
2091    base::ListValue urls;
2092    for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2093      urls.Append(base::Value::CreateStringValue(kRestoredURLs[i]));
2094      expected_urls_.push_back(GURL(kRestoredURLs[i]));
2095    }
2096    PolicyMap policies;
2097    policies.Set(
2098        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2099        base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs),
2100        NULL);
2101    policies.Set(
2102        key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2103        urls.DeepCopy(), NULL);
2104    provider_.UpdateChromePolicy(policies);
2105  }
2106
2107  void NTP() {
2108    // Verifies that policy can set the startup page to the NTP.
2109    PolicyMap policies;
2110    policies.Set(
2111        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2112        base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab),
2113        NULL);
2114    provider_.UpdateChromePolicy(policies);
2115    expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2116  }
2117
2118  void Last() {
2119    // Verifies that policy can set the startup pages to the last session.
2120    PolicyMap policies;
2121    policies.Set(
2122        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2123        base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast),
2124        NULL);
2125    provider_.UpdateChromePolicy(policies);
2126    // This should restore the tabs opened at PRE_RunTest below.
2127    for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2128      expected_urls_.push_back(GURL(kRestoredURLs[i]));
2129  }
2130
2131  std::vector<GURL> expected_urls_;
2132};
2133
2134IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2135  // Open some tabs to verify if they are restored after the browser restarts.
2136  // Most policy settings override this, except kPrefValueLast which enforces
2137  // a restore.
2138  ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
2139  for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
2140    content::WindowedNotificationObserver observer(
2141        content::NOTIFICATION_LOAD_STOP,
2142        content::NotificationService::AllSources());
2143    chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
2144                                  content::PAGE_TRANSITION_LINK);
2145    observer.Wait();
2146  }
2147}
2148
2149IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
2150#if defined(OS_WIN) && defined(USE_ASH)
2151  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2152  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2153    return;
2154#endif
2155
2156  TabStripModel* model = browser()->tab_strip_model();
2157  int size = static_cast<int>(expected_urls_.size());
2158  EXPECT_EQ(size, model->count());
2159  for (int i = 0; i < size && i < model->count(); ++i) {
2160    EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
2161  }
2162}
2163
2164INSTANTIATE_TEST_CASE_P(
2165    RestoreOnStartupPolicyTestInstance,
2166    RestoreOnStartupPolicyTest,
2167    testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
2168                    &RestoreOnStartupPolicyTest::HomepageIsNTP,
2169                    &RestoreOnStartupPolicyTest::ListOfURLs,
2170                    &RestoreOnStartupPolicyTest::NTP,
2171                    &RestoreOnStartupPolicyTest::Last));
2172
2173// Similar to PolicyTest but sets a couple of policies before the browser is
2174// started.
2175class PolicyStatisticsCollectorTest : public PolicyTest {
2176 public:
2177  PolicyStatisticsCollectorTest() {}
2178  virtual ~PolicyStatisticsCollectorTest() {}
2179
2180  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2181    PolicyTest::SetUpInProcessBrowserTestFixture();
2182    PolicyMap policies;
2183    policies.Set(
2184        key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2185        base::Value::CreateBooleanValue(true), NULL);
2186    policies.Set(
2187        key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2188        base::Value::CreateBooleanValue(false), NULL);
2189    policies.Set(
2190        key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2191        base::Value::CreateStringValue("http://chromium.org"), NULL);
2192    provider_.UpdateChromePolicy(policies);
2193  }
2194};
2195
2196IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
2197  // Verifies that policy usage histograms are collected at startup.
2198
2199  // BrowserPolicyConnector::Init() has already been called. Make sure the
2200  // CompleteInitialization() task has executed as well.
2201  content::RunAllPendingInMessageLoop();
2202
2203  GURL kAboutHistograms = GURL(std::string(chrome::kAboutScheme) +
2204                               std::string(content::kStandardSchemeSeparator) +
2205                               std::string(content::kChromeUIHistogramHost));
2206  ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
2207  content::WebContents* contents =
2208      browser()->tab_strip_model()->GetActiveWebContents();
2209  std::string text;
2210  ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2211      contents,
2212      "var nodes = document.querySelectorAll('body > pre');"
2213      "var result = '';"
2214      "for (var i = 0; i < nodes.length; ++i) {"
2215      "  var text = nodes[i].innerHTML;"
2216      "  if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
2217      "    result = text;"
2218      "    break;"
2219      "  }"
2220      "}"
2221      "domAutomationController.send(result);",
2222      &text));
2223  ASSERT_FALSE(text.empty());
2224  const std::string kExpectedLabel =
2225      "Histogram: Enterprise.Policies recorded 3 samples";
2226  EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
2227  // HomepageLocation has policy ID 1.
2228  EXPECT_NE(std::string::npos, text.find("<br>1   ---"));
2229  // ShowHomeButton has policy ID 35.
2230  EXPECT_NE(std::string::npos, text.find("<br>35  ---"));
2231  // BookmarkBarEnabled has policy ID 82.
2232  EXPECT_NE(std::string::npos, text.find("<br>82  ---"));
2233}
2234
2235class MediaStreamDevicesControllerBrowserTest
2236    : public PolicyTest,
2237      public testing::WithParamInterface<bool> {
2238 public:
2239  MediaStreamDevicesControllerBrowserTest()
2240      : request_url_allowed_via_whitelist_(false) {
2241    policy_value_ = GetParam();
2242  }
2243  virtual ~MediaStreamDevicesControllerBrowserTest() {}
2244
2245  // Configure a given policy map.
2246  // The |policy_name| is the name of either the audio or video capture allow
2247  // policy and must never be NULL.
2248  // |whitelist_policy| and |allow_rule| are optional.  If NULL, no whitelist
2249  // policy is set.  If non-NULL, the request_url_ will be set to be non empty
2250  // and the whitelist policy is set to contain either the |allow_rule| (if
2251  // non-NULL) or an "allow all" wildcard.
2252  void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
2253                          const char* whitelist_policy,
2254                          const char* allow_rule) {
2255    policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2256        base::Value::CreateBooleanValue(policy_value_), NULL);
2257
2258    if (whitelist_policy) {
2259      // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
2260      // in the media exceptions UI.
2261      // See discussion here: https://codereview.chromium.org/15738004/
2262      CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
2263
2264      // Add an entry to the whitelist that allows the specified URL regardless
2265      // of the setting of kAudioCapturedAllowed.
2266      request_url_ = GURL("http://www.example.com/foo");
2267      base::ListValue* list = new base::ListValue();
2268      if (allow_rule) {
2269        list->AppendString(allow_rule);
2270        request_url_allowed_via_whitelist_ = true;
2271      } else {
2272        list->AppendString(ContentSettingsPattern::Wildcard().ToString());
2273        // We should ignore all wildcard entries in the whitelist, so even
2274        // though we've added an entry, it should be ignored and our expectation
2275        // is that the request has not been allowed via the whitelist.
2276        request_url_allowed_via_whitelist_ = false;
2277      }
2278      policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
2279                    POLICY_SCOPE_USER, list, NULL);
2280    }
2281  }
2282
2283  void Accept(const content::MediaStreamDevices& devices,
2284              scoped_ptr<content::MediaStreamUI> ui) {
2285    if (policy_value_ || request_url_allowed_via_whitelist_) {
2286      ASSERT_EQ(1U, devices.size());
2287      ASSERT_EQ("fake_dev", devices[0].id);
2288    } else {
2289      ASSERT_EQ(0U, devices.size());
2290    }
2291  }
2292
2293  void FinishAudioTest() {
2294    content::MediaStreamRequest request(0, 0, 0, std::string(),
2295                                        request_url_.GetOrigin(),
2296                                        content::MEDIA_DEVICE_ACCESS,
2297                                        std::string(), std::string(),
2298                                        content::MEDIA_DEVICE_AUDIO_CAPTURE,
2299                                        content::MEDIA_NO_SERVICE);
2300    // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2301    // and microphone permissions at the same time.
2302    MediaStreamDevicesController controller(
2303        browser()->tab_strip_model()->GetActiveWebContents(), request,
2304        base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2305    controller.Accept(false);
2306
2307    base::MessageLoop::current()->QuitWhenIdle();
2308  }
2309
2310  void FinishVideoTest() {
2311    // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2312    // and microphone permissions at the same time.
2313    content::MediaStreamRequest request(0, 0, 0, std::string(),
2314                                        request_url_.GetOrigin(),
2315                                        content::MEDIA_DEVICE_ACCESS,
2316                                        std::string(),
2317                                        std::string(),
2318                                        content::MEDIA_NO_SERVICE,
2319                                        content::MEDIA_DEVICE_VIDEO_CAPTURE);
2320    MediaStreamDevicesController controller(
2321        browser()->tab_strip_model()->GetActiveWebContents(), request,
2322        base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2323    controller.Accept(false);
2324
2325    base::MessageLoop::current()->QuitWhenIdle();
2326  }
2327
2328  bool policy_value_;
2329  bool request_url_allowed_via_whitelist_;
2330  GURL request_url_;
2331  static const char kExampleRequestPattern[];
2332};
2333
2334// static
2335const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
2336    "http://[*.]example.com/";
2337
2338IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2339                       AudioCaptureAllowed) {
2340  content::MediaStreamDevices audio_devices;
2341  content::MediaStreamDevice fake_audio_device(
2342      content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2343  audio_devices.push_back(fake_audio_device);
2344
2345  PolicyMap policies;
2346  ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
2347  UpdateProviderPolicy(policies);
2348
2349  content::BrowserThread::PostTaskAndReply(
2350      content::BrowserThread::IO, FROM_HERE,
2351      base::Bind(&MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged,
2352                 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2353                 audio_devices),
2354      base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2355                 this));
2356
2357  base::MessageLoop::current()->Run();
2358}
2359
2360IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2361                       AudioCaptureAllowedUrls) {
2362  content::MediaStreamDevices audio_devices;
2363  content::MediaStreamDevice fake_audio_device(
2364      content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2365  audio_devices.push_back(fake_audio_device);
2366
2367  const char* allow_pattern[] = {
2368    kExampleRequestPattern,
2369    // This will set an allow-all policy whitelist.  Since we do not allow
2370    // setting an allow-all entry in the whitelist, this entry should be ignored
2371    // and therefore the request should be denied.
2372    NULL,
2373  };
2374
2375  for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2376    PolicyMap policies;
2377    ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
2378                       key::kAudioCaptureAllowedUrls, allow_pattern[i]);
2379    UpdateProviderPolicy(policies);
2380
2381    content::BrowserThread::PostTaskAndReply(
2382        content::BrowserThread::IO, FROM_HERE,
2383        base::Bind(
2384            &MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged,
2385            base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2386            audio_devices),
2387        base::Bind(
2388            &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2389            this));
2390
2391    base::MessageLoop::current()->Run();
2392  }
2393}
2394
2395IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2396                       VideoCaptureAllowed) {
2397  content::MediaStreamDevices video_devices;
2398  content::MediaStreamDevice fake_video_device(
2399      content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2400  video_devices.push_back(fake_video_device);
2401
2402  PolicyMap policies;
2403  ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
2404  UpdateProviderPolicy(policies);
2405
2406  content::BrowserThread::PostTaskAndReply(
2407      content::BrowserThread::IO, FROM_HERE,
2408      base::Bind(&MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged,
2409                 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2410                 video_devices),
2411      base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2412                 this));
2413
2414  base::MessageLoop::current()->Run();
2415}
2416
2417IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2418                       VideoCaptureAllowedUrls) {
2419  content::MediaStreamDevices video_devices;
2420  content::MediaStreamDevice fake_video_device(
2421      content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2422  video_devices.push_back(fake_video_device);
2423
2424  const char* allow_pattern[] = {
2425    kExampleRequestPattern,
2426    // This will set an allow-all policy whitelist.  Since we do not allow
2427    // setting an allow-all entry in the whitelist, this entry should be ignored
2428    // and therefore the request should be denied.
2429    NULL,
2430  };
2431
2432  for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2433    PolicyMap policies;
2434    ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
2435                       key::kVideoCaptureAllowedUrls, allow_pattern[i]);
2436    UpdateProviderPolicy(policies);
2437
2438    content::BrowserThread::PostTaskAndReply(
2439        content::BrowserThread::IO, FROM_HERE,
2440        base::Bind(
2441            &MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged,
2442            base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2443            video_devices),
2444        base::Bind(
2445            &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2446            this));
2447
2448    base::MessageLoop::current()->Run();
2449  }
2450}
2451
2452INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
2453                        MediaStreamDevicesControllerBrowserTest,
2454                        testing::Bool());
2455
2456#if !defined(OS_CHROMEOS)
2457// Similar to PolicyTest but sets the proper policy before the browser is
2458// started.
2459class PolicyVariationsServiceTest : public PolicyTest {
2460 public:
2461  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2462    PolicyTest::SetUpInProcessBrowserTestFixture();
2463    PolicyMap policies;
2464    policies.Set(
2465        key::kVariationsRestrictParameter,
2466        POLICY_LEVEL_MANDATORY,
2467        POLICY_SCOPE_USER,
2468        base::Value::CreateStringValue("restricted"),
2469        NULL);
2470    provider_.UpdateChromePolicy(policies);
2471  }
2472};
2473
2474IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
2475  const std::string default_variations_url =
2476      chrome_variations::VariationsService::
2477          GetDefaultVariationsServerURLForTesting();
2478
2479  const GURL url =
2480      chrome_variations::VariationsService::GetVariationsServerURL(
2481          g_browser_process->local_state());
2482  EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
2483  std::string value;
2484  EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
2485  EXPECT_EQ("restricted", value);
2486}
2487#endif
2488
2489}  // namespace policy
2490