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