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