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