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