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