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