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