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