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