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