blob: 2e77e2d8a394d35388eeb58de354ce276463aba2 [file] [log] [blame]
[email protected]3757c7d2012-07-23 11:24:361// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
avib896c712015-12-26 02:10:435#include <stddef.h>
6#include <stdint.h>
dcheng08cfe9ba2016-04-14 17:46:457
[email protected]88ce3e72012-09-11 08:34:228#include <algorithm>
dcheng08cfe9ba2016-04-14 17:46:459#include <memory>
[email protected]b561aab2012-08-27 20:17:4910#include <string>
dchengcf738a92015-12-31 16:11:4511#include <utility>
[email protected]2321f0b2012-09-10 01:51:5112#include <vector>
[email protected]b561aab2012-08-27 20:17:4913
John Abd-El-Malek580bc96a52018-08-10 02:24:4714#include "base/atomic_ref_count.h"
[email protected]38a4db92012-08-29 09:36:0515#include "base/bind.h"
[email protected]7ea48702012-09-03 20:41:0616#include "base/bind_helpers.h"
[email protected]aecb6082013-07-09 14:29:4117#include "base/callback.h"
rsleevi96356f82016-06-30 09:01:2018#include "base/callback_helpers.h"
[email protected]88ce3e72012-09-11 08:34:2219#include "base/command_line.h"
Carlos IL798c47c8ce2018-11-26 17:30:4120#include "base/feature_list.h"
[email protected]25a4c1c2013-06-08 04:53:3621#include "base/files/file_enumerator.h"
[email protected]57999812013-02-24 05:40:5222#include "base/files/file_path.h"
thestig18dfb7a52014-08-26 10:44:0423#include "base/files/file_util.h"
[email protected]ea1a3f62012-11-16 20:34:2324#include "base/files/scoped_temp_dir.h"
Sorin Jianu55587d32018-11-14 21:43:2725#include "base/json/json_reader.h"
dcheng08cfe9ba2016-04-14 17:46:4526#include "base/memory/ptr_util.h"
[email protected]ec29ec032012-09-10 18:27:0927#include "base/memory/ref_counted.h"
Alexander Timin4f9c35c2018-11-01 20:15:2028#include "base/message_loop/message_loop.h"
Gabriel Charettebbb7d2f2018-04-24 07:58:0629#include "base/message_loop/message_loop_current.h"
Mathieu Perreault18170a42018-05-17 12:48:1530#include "base/metrics/histogram_base.h"
31#include "base/metrics/histogram_samples.h"
32#include "base/metrics/statistics_recorder.h"
[email protected]2321f0b2012-09-10 01:51:5133#include "base/path_service.h"
[email protected]161245d2013-01-09 14:28:1134#include "base/run_loop.h"
Avi Drissman5f0fb8c2018-12-25 23:20:4935#include "base/stl_util.h"
Clark DuVall385b5a52018-06-14 21:33:3236#include "base/strings/strcat.h"
[email protected]76fb05c2013-06-11 04:38:0537#include "base/strings/string16.h"
felt2d3f65e2015-05-18 15:26:0438#include "base/strings/string_number_conversions.h"
[email protected]76fb05c2013-06-11 04:38:0539#include "base/strings/string_util.h"
40#include "base/strings/stringprintf.h"
[email protected]e309f312013-06-07 21:50:0841#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3342#include "base/task/post_task.h"
John Abd-El-Malek9fb60492018-08-02 04:28:5043#include "base/test/bind_test_util.h"
chaopeng01e3b252017-10-18 22:33:3744#include "base/test/scoped_feature_list.h"
[email protected]d1251212012-08-29 13:15:5945#include "base/test/test_file_util.h"
jam3f2d3932017-04-26 20:28:5146#include "base/threading/thread_restrictions.h"
[email protected]ff54ace22013-06-28 01:26:2147#include "base/time/time.h"
[email protected]2321f0b2012-09-10 01:51:5148#include "base/values.h"
avib896c712015-12-26 02:10:4349#include "build/build_config.h"
[email protected]b3fc7b72012-08-28 15:04:0450#include "chrome/app/chrome_command_ids.h"
[email protected]6b9dafc2013-08-30 15:41:5951#include "chrome/browser/background/background_contents_service.h"
[email protected]3757c7d2012-07-23 11:24:3652#include "chrome/browser/browser_process.h"
[email protected]25ff0862013-07-12 00:59:0353#include "chrome/browser/chrome_notification_types.h"
Bartosz Fabianowski6979a6d2018-05-24 13:29:2054#include "chrome/browser/chromeos/policy/configuration_policy_handler_chromeos.h"
wafflesa4f53d42017-02-07 01:19:3155#include "chrome/browser/component_updater/chrome_component_updater_configurator.h"
Clark DuVall385b5a52018-06-14 21:33:3256#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
[email protected]d017a702013-01-27 23:51:3657#include "chrome/browser/content_settings/tab_specific_content_settings.h"
[email protected]d118ad72014-07-21 14:07:0158#include "chrome/browser/devtools/devtools_window_testing.h"
[email protected]7ea48702012-09-03 20:41:0659#include "chrome/browser/download/download_prefs.h"
Michael Giuffrida9e1a9f82017-08-08 14:23:2960#include "chrome/browser/extensions/api/chrome_extensions_api_client.h"
limasdfc83e0b72017-03-03 17:08:3561#include "chrome/browser/extensions/chrome_test_extension_loader.h"
[email protected]ec29ec032012-09-10 18:27:0962#include "chrome/browser/extensions/crx_installer.h"
binjincccacef2014-10-13 19:00:2063#include "chrome/browser/extensions/extension_management_constants.h"
binjin8e3d0182014-12-04 16:44:2864#include "chrome/browser/extensions/extension_management_test_util.h"
[email protected]ec29ec032012-09-10 18:27:0965#include "chrome/browser/extensions/extension_service.h"
Devlin Cronin5e9387c32018-04-20 04:22:0366#include "chrome/browser/extensions/install_verifier.h"
joaodasilva30c8be92014-10-23 23:40:4167#include "chrome/browser/extensions/shared_module_service.h"
[email protected]ec1b3e712013-05-25 14:29:1668#include "chrome/browser/extensions/unpacked_installer.h"
[email protected]044e86992014-01-24 22:59:1169#include "chrome/browser/extensions/updater/extension_cache_fake.h"
[email protected]6b6a6e62013-05-28 19:33:3770#include "chrome/browser/extensions/updater/extension_updater.h"
[email protected]4a8adfa02013-03-19 22:37:4671#include "chrome/browser/infobars/infobar_service.h"
fahle66e7ff2015-04-23 19:38:3072#include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
mcasasa2023ab2016-09-08 01:06:3673#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
74#include "chrome/browser/media/webrtc/media_stream_devices_controller.h"
Elad Alon6bd69cb2018-08-06 18:20:4575#include "chrome/browser/media/webrtc/webrtc_event_log_manager.h"
[email protected]27ef988d2014-08-01 17:00:4076#include "chrome/browser/net/prediction_options.h"
Min Qinb4bba9d2018-08-21 18:26:5477#include "chrome/browser/net/system_network_context_manager.h"
raymes2d2d7d72017-03-06 22:16:3378#include "chrome/browser/permissions/permission_request_manager.h"
Scott Violetfdd6f352018-01-12 19:12:2979#include "chrome/browser/policy/chrome_browser_policy_connector.h"
[email protected]f97bd482013-11-21 13:04:2880#include "chrome/browser/policy/profile_policy_connector.h"
[email protected]88ce3e72012-09-11 08:34:2281#include "chrome/browser/prefs/session_startup_pref.h"
[email protected]3757c7d2012-07-23 11:24:3682#include "chrome/browser/profiles/profile.h"
Francois Doray8059c542018-07-05 21:16:2083#include "chrome/browser/resource_coordinator/tab_load_tracker_test_support.h"
Jialiu Lin219b97862018-01-27 02:39:5984#include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
Conley Owensaafcf122018-02-26 18:53:5185#include "chrome/browser/search/search.h"
[email protected]771c4b92012-08-29 10:19:2786#include "chrome/browser/search_engines/template_url_service_factory.h"
felt2d3f65e2015-05-18 15:26:0487#include "chrome/browser/ssl/ssl_blocking_page.h"
avi24d693f2016-08-06 18:03:5288#include "chrome/browser/task_manager/task_manager_interface.h"
[email protected]255ab972014-06-04 12:14:2289#include "chrome/browser/translate/chrome_translate_client.h"
[email protected]546f5d62014-02-10 17:54:5090#include "chrome/browser/translate/translate_service.h"
[email protected]3757c7d2012-07-23 11:24:3691#include "chrome/browser/ui/bookmarks/bookmark_bar.h"
92#include "chrome/browser/ui/browser.h"
[email protected]b3fc7b72012-08-28 15:04:0493#include "chrome/browser/ui/browser_commands.h"
[email protected]e4171782013-02-14 18:22:5794#include "chrome/browser/ui/browser_list.h"
[email protected]850b4be2012-08-28 15:10:3495#include "chrome/browser/ui/browser_tabstrip.h"
[email protected]771c4b92012-08-29 10:19:2796#include "chrome/browser/ui/browser_window.h"
[email protected]d57ce6a2014-07-03 15:39:2397#include "chrome/browser/ui/location_bar/location_bar.h"
timlohfa10d432017-06-20 00:50:2398#include "chrome/browser/ui/permission_bubble/mock_permission_prompt_factory.h"
Weilun Shib59ba592018-08-07 22:42:3599#include "chrome/browser/ui/search/instant_test_utils.h"
100#include "chrome/browser/ui/search/local_ntp_test_utils.h"
[email protected]88ce3e72012-09-11 08:34:22101#include "chrome/browser/ui/tabs/tab_strip_model.h"
Lei Zhangc5b042c2017-11-11 00:39:23102#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
Hector Carmona1e62e352019-06-24 19:18:17103#include "chrome/browser/ui/webui/welcome/nux_helper.h"
Reilly Grant6f18e1f2018-04-03 02:03:22104#include "chrome/browser/usb/usb_chooser_context.h"
105#include "chrome/browser/usb/usb_chooser_context_factory.h"
Alexander Hendrich9ce49262018-05-29 13:35:46106#include "chrome/common/chrome_constants.h"
timlohfa10d432017-06-20 00:50:23107#include "chrome/common/chrome_features.h"
[email protected]69fe7ac2013-01-02 21:33:59108#include "chrome/common/chrome_paths.h"
[email protected]2bfe6ce2012-09-13 09:47:39109#include "chrome/common/chrome_switches.h"
[email protected]ec29ec032012-09-10 18:27:09110#include "chrome/common/extensions/extension_constants.h"
Konstantin Ganenkoae1129c2017-09-15 16:28:59111#include "chrome/common/extensions/extension_test_util.h"
Giovanni Ortuño Urquidi77b5bf72018-08-23 06:43:29112#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
John Abd-El-Malek9fb60492018-08-02 04:28:50113#include "chrome/common/net/safe_search_util.h"
[email protected]3757c7d2012-07-23 11:24:36114#include "chrome/common/pref_names.h"
[email protected]bb34f262012-09-05 09:09:46115#include "chrome/common/url_constants.h"
Christopher Lam96b044c2017-11-24 03:29:46116#include "chrome/common/web_application_info.h"
Weilun Shib59ba592018-08-07 22:42:35117#include "chrome/common/webui_url_constants.h"
[email protected]af39f002014-08-22 10:18:18118#include "chrome/grit/generated_resources.h"
Weilun Shib59ba592018-08-07 22:42:35119#include "chrome/grit/locale_settings.h"
[email protected]3757c7d2012-07-23 11:24:36120#include "chrome/test/base/in_process_browser_test.h"
thestigf80564462015-09-29 23:12:08121#include "chrome/test/base/search_test_utils.h"
Alexander Hendrich9ce49262018-05-29 13:35:46122#include "chrome/test/base/testing_profile.h"
[email protected]3757c7d2012-07-23 11:24:36123#include "chrome/test/base/ui_test_utils.h"
brettwe1f0af8b2015-10-09 21:30:46124#include "components/bookmarks/common/bookmark_pref_names.h"
dullweber303f4442017-03-03 11:50:19125#include "components/browsing_data/core/pref_names.h"
sorin0b99b8d2016-08-22 20:40:53126#include "components/component_updater/component_updater_service.h"
Antonio Gomesb6162502018-06-28 20:21:55127#include "components/component_updater/component_updater_switches.h"
Clark DuVall385b5a52018-06-14 21:33:32128#include "components/content_settings/core/browser/host_content_settings_map.h"
mukai077089f2014-09-11 18:41:52129#include "components/content_settings/core/common/content_settings.h"
vasiliif62dbf92014-09-05 10:23:13130#include "components/content_settings/core/common/content_settings_pattern.h"
brettwe1f0af8b2015-10-09 21:30:46131#include "components/content_settings/core/common/pref_names.h"
Min Qina9f487872018-02-09 20:43:23132#include "components/download/public/common/download_item.h"
John Abd-El-Malekd2b62ee2018-11-20 07:43:34133#include "components/google/core/common/google_util.h"
[email protected]051655ad2014-04-18 15:09:41134#include "components/infobars/core/infobar.h"
Ran Ji73f3b432018-07-15 22:10:27135#include "components/language/core/browser/pref_names.h"
John Abd-El-Malekd2b62ee2018-11-20 07:43:34136#include "components/network_session_configurator/common/network_switches.h"
estark80618c32017-05-24 02:48:31137#include "components/network_time/network_time_tracker.h"
blundell2102f7c2015-07-09 10:00:53138#include "components/omnibox/browser/autocomplete_controller.h"
blundell7dbd3792015-08-05 15:14:19139#include "components/omnibox/browser/omnibox_edit_model.h"
140#include "components/omnibox/browser/omnibox_view.h"
[email protected]97275822014-01-21 19:30:36141#include "components/policy/core/browser/browser_policy_connector.h"
[email protected]c4a138a2013-11-21 19:54:57142#include "components/policy/core/common/external_data_fetcher.h"
[email protected]f20a3a22013-12-03 16:12:37143#include "components/policy/core/common/mock_configuration_policy_provider.h"
[email protected]c4a138a2013-11-21 19:54:57144#include "components/policy/core/common/policy_map.h"
[email protected]425e3372013-12-17 09:35:43145#include "components/policy/core/common/policy_pref_names.h"
[email protected]76b4b152013-12-08 21:10:04146#include "components/policy/core/common/policy_service.h"
147#include "components/policy/core/common/policy_service_impl.h"
fhorschig64834b712015-09-21 14:20:23148#include "components/policy/core/common/policy_types.h"
brettw39d6ba42016-08-24 16:56:38149#include "components/policy/policy_constants.h"
brettwb1fc1b82016-02-02 00:19:08150#include "components/prefs/pref_service.h"
Luna Luaacaa90f2018-03-13 15:22:08151#include "components/safe_browsing/features.h"
[email protected]d550cb02014-06-25 06:48:11152#include "components/search_engines/template_url.h"
[email protected]bf5c532d2014-07-05 00:29:53153#include "components/search_engines/template_url_service.h"
jialiula2c069252017-01-05 18:13:04154#include "components/security_interstitials/content/security_interstitial_page.h"
Carlos IL0ea4e592018-05-11 01:51:57155#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
felt9de47c52015-11-24 03:29:57156#include "components/security_interstitials/core/controller_client.h"
David Roger618d1c62019-01-15 12:55:24157#include "components/signin/core/browser/account_info.h"
blundell02d46ab2015-12-03 13:23:57158#include "components/strings/grit/components_strings.h"
[email protected]5e625b02014-06-11 09:34:27159#include "components/translate/core/browser/language_state.h"
[email protected]dbe9bfa2014-06-02 16:01:29160#include "components/translate/core/browser/translate_infobar_delegate.h"
Thomas Tangl6703fceb2018-07-18 15:54:25161#include "components/unified_consent/pref_names.h"
Sorin Jianu4e0b41d2019-02-20 17:21:58162#include "components/update_client/net/url_loader_post_interceptor.h"
sorin2892f7212016-11-07 18:59:43163#include "components/update_client/update_client.h"
sorin7b8650522016-11-02 18:23:41164#include "components/update_client/update_client_errors.h"
guidouca055a542016-08-11 11:15:53165#include "components/user_prefs/user_prefs.h"
blundell0300cdea2015-09-03 12:47:44166#include "components/variations/service/variations_service.h"
Luke Zielinski389909fa2018-06-10 02:10:56167#include "components/variations/variations_params_manager.h"
sdefresne9fb67692015-08-03 18:48:22168#include "components/version_info/version_info.h"
[email protected]d1251212012-08-29 13:15:59169#include "content/public/browser/browser_context.h"
Eric Seckler8652dcd52018-09-20 10:42:28170#include "content/public/browser/browser_task_traits.h"
[email protected]38a4db92012-08-29 09:36:05171#include "content/public/browser/browser_thread.h"
[email protected]2321f0b2012-09-10 01:51:51172#include "content/public/browser/child_process_data.h"
[email protected]d1251212012-08-29 13:15:59173#include "content/public/browser/download_manager.h"
[email protected]f5b7f6e2013-12-10 13:57:32174#include "content/public/browser/gpu_data_manager.h"
estark86642d602015-04-09 20:39:16175#include "content/public/browser/interstitial_page.h"
[email protected]6b9dafc2013-08-30 15:41:59176#include "content/public/browser/notification_details.h"
177#include "content/public/browser/notification_observer.h"
[email protected]9a8764b2013-03-27 16:18:09178#include "content/public/browser/notification_registrar.h"
[email protected]850b4be2012-08-28 15:10:34179#include "content/public/browser/notification_service.h"
[email protected]7ea48702012-09-03 20:41:06180#include "content/public/browser/notification_source.h"
[email protected]771c4b92012-08-29 10:19:27181#include "content/public/browser/notification_types.h"
estark86642d602015-04-09 20:39:16182#include "content/public/browser/render_frame_host.h"
[email protected]7c60f5042013-02-14 03:39:32183#include "content/public/browser/render_process_host.h"
[email protected]ea826362012-09-05 23:31:37184#include "content/public/browser/render_view_host.h"
avif9ab5d942015-10-15 14:05:44185#include "content/public/browser/render_widget_host.h"
Doug Turner9e79cf0c2018-04-05 21:32:30186#include "content/public/browser/storage_partition.h"
Ken Rockoteff2b822019-06-20 22:56:53187#include "content/public/browser/system_connector.h"
[email protected]38a4db92012-08-29 09:36:05188#include "content/public/browser/web_contents.h"
[email protected]73270292013-08-09 03:48:07189#include "content/public/common/content_constants.h"
John Abd-El-Malek39d0a672018-09-28 22:14:05190#include "content/public/common/content_features.h"
[email protected]2321f0b2012-09-10 01:51:51191#include "content/public/common/content_paths.h"
jyasskin98bdd3992016-02-26 20:25:45192#include "content/public/common/content_switches.h"
John Abd-El-Malek9dba1ad2018-10-27 02:22:14193#include "content/public/common/network_service_util.h"
[email protected]6b9dafc2013-08-30 15:41:59194#include "content/public/common/result_codes.h"
Doug Turner9e79cf0c2018-04-05 21:32:30195#include "content/public/common/service_names.mojom.h"
[email protected]bb34f262012-09-05 09:09:46196#include "content/public/common/url_constants.h"
François Beaufort4f8107d2018-03-05 12:12:10197#include "content/public/common/web_preferences.h"
[email protected]b561aab2012-08-27 20:17:49198#include "content/public/test/browser_test_utils.h"
[email protected]d1251212012-08-29 13:15:59199#include "content/public/test/download_test_observer.h"
[email protected]9a8764b2013-03-27 16:18:09200#include "content/public/test/mock_notification_observer.h"
Doug Turner9e79cf0c2018-04-05 21:32:30201#include "content/public/test/network_service_test_helper.h"
Lukasz Anforowicz907b6ac2019-06-13 01:49:08202#include "content/public/test/no_renderer_crashes_assertion.h"
Kunihiko Sakamotof586da62019-03-28 03:03:04203#include "content/public/test/signed_exchange_browser_test_helper.h"
[email protected]d1208ba32012-11-08 11:10:33204#include "content/public/test/test_navigation_observer.h"
[email protected]771c4b92012-08-29 10:19:27205#include "content/public/test/test_utils.h"
John Abd-El-Malek9fb60492018-08-02 04:28:50206#include "content/public/test/url_loader_interceptor.h"
jyasskin98bdd3992016-02-26 20:25:45207#include "device/bluetooth/bluetooth_adapter_factory.h"
208#include "device/bluetooth/test/mock_bluetooth_adapter.h"
Michael Giuffrida9e1a9f82017-08-08 14:23:29209#include "extensions/browser/api/messaging/messaging_delegate.h"
Devlin Croninbffe949eb2018-01-12 03:03:40210#include "extensions/browser/disable_reason.h"
rdevlin.cronin66209492015-06-10 20:44:05211#include "extensions/browser/extension_dialog_auto_confirm.h"
[email protected]22401dc2014-03-21 01:38:57212#include "extensions/browser/extension_host.h"
binjin8e3d0182014-12-04 16:44:28213#include "extensions/browser/extension_prefs.h"
joaodasilva30c8be92014-10-23 23:40:41214#include "extensions/browser/extension_registry.h"
[email protected]59b0e602014-01-30 00:41:24215#include "extensions/browser/extension_system.h"
[email protected]98b6d942013-11-10 00:34:07216#include "extensions/browser/process_manager.h"
asargent75f55482016-06-08 15:53:54217#include "extensions/browser/scoped_ignore_content_verifier_for_test.h"
joaodasilva30c8be92014-10-23 23:40:41218#include "extensions/browser/test_extension_registry_observer.h"
[email protected]e43c61f2014-07-20 21:46:34219#include "extensions/browser/uninstall_reason.h"
[email protected]e4452d32013-11-15 23:07:41220#include "extensions/common/extension.h"
[email protected]289c44b2013-12-17 03:26:57221#include "extensions/common/extension_set.h"
rdevlin.cronin41227532016-07-13 21:24:34222#include "extensions/common/features/feature_channel.h"
joaodasilva30c8be92014-10-23 23:40:41223#include "extensions/common/manifest_handlers/shared_module_info.h"
Toni Barzicc45d9b12017-07-25 02:53:36224#include "extensions/common/switches.h"
Christopher Lam96b044c2017-11-24 03:29:46225#include "extensions/common/value_builder.h"
Scott Violeta35f9a42018-03-22 22:00:44226#include "media/media_buildflags.h"
Ryan Sleevic8889d02018-04-06 17:57:05227#include "net/base/hash_value.h"
[email protected]d1208ba32012-11-08 11:10:33228#include "net/base/net_errors.h"
[email protected]a29ad212013-05-02 20:18:54229#include "net/base/url_util.h"
Ryan Sleevic8889d02018-04-06 17:57:05230#include "net/cert/x509_util.h"
Yuzhu Shen6ccfd562017-10-27 16:38:18231#include "net/dns/mock_host_resolver.h"
[email protected]02e09be2012-09-09 16:09:29232#include "net/http/http_stream_factory.h"
rsleevi96356f82016-06-30 09:01:20233#include "net/http/transport_security_state.h"
svaldeza01f7d92015-11-18 17:47:56234#include "net/test/embedded_test_server/embedded_test_server.h"
estark80618c32017-05-24 02:48:31235#include "net/test/embedded_test_server/http_request.h"
236#include "net/test/embedded_test_server/http_response.h"
xunjieli2906f152014-09-12 00:08:23237#include "net/test/url_request/url_request_failed_job.h"
xunjieli0332c192014-09-10 23:23:31238#include "net/test/url_request/url_request_mock_http_job.h"
Maksim Ivanoveaac2ff2018-04-16 16:23:24239#include "net/url_request/test_url_request_interceptor.h"
[email protected]38a4db92012-08-29 09:36:05240#include "net/url_request/url_request.h"
241#include "net/url_request/url_request_filter.h"
pauljensen754dde232015-06-03 05:47:29242#include "net/url_request/url_request_interceptor.h"
Donna Wu4dc9df32019-05-20 03:56:21243#include "services/device/public/cpp/test/fake_usb_device_info.h"
Doug Turner9e79cf0c2018-04-05 21:32:30244#include "services/network/public/cpp/features.h"
245#include "services/network/public/cpp/network_switches.h"
Matt Menked476edd2018-05-03 16:43:50246#include "services/network/public/mojom/network_service.mojom.h"
Doug Turner9e79cf0c2018-04-05 21:32:30247#include "services/network/public/mojom/network_service_test.mojom.h"
248#include "services/service_manager/public/cpp/connector.h"
[email protected]3757c7d2012-07-23 11:24:36249#include "testing/gmock/include/gmock/gmock.h"
250#include "testing/gtest/include/gtest/gtest.h"
Antonio Gomes0d42960a2019-06-05 12:35:51251#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
Blink Reformata30d4232018-04-07 15:31:06252#include "third_party/blink/public/platform/web_input_event.h"
[email protected]f900367b22012-09-11 16:08:36253#include "ui/base/l10n/l10n_util.h"
Sylvain Defresnec6ccc77d2014-09-19 10:19:35254#include "ui/base/page_transition_types.h"
[email protected]f900367b22012-09-11 16:08:36255#include "ui/base/resource/resource_bundle.h"
rjkroege72f8154f2016-10-29 00:49:02256#include "ui/display/manager/display_manager.h"
[email protected]761fa4702013-07-02 15:25:15257#include "url/gurl.h"
jyasskin98bdd3992016-02-26 20:25:45258#include "url/origin.h"
[email protected]3757c7d2012-07-23 11:24:36259
[email protected]7ea48702012-09-03 20:41:06260#if defined(OS_CHROMEOS)
Evan Stade7d0e8232017-10-04 02:01:36261#include "ash/public/cpp/ash_switches.h"
[email protected]7ea48702012-09-03 20:41:06262#include "ash/shell.h"
[email protected]2968e4f7452013-06-10 17:39:07263#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
264#include "chrome/browser/chromeos/accessibility/magnification_manager.h"
Qiang Xu92eabd42018-06-27 16:20:05265#include "chrome/browser/chromeos/accessibility/magnifier_type.h"
hidehiko5d944082016-11-18 06:16:04266#include "chrome/browser/chromeos/arc/arc_session_manager.h"
Sam McNally5edde0a2019-02-27 11:10:03267#include "chrome/browser/chromeos/drive/drive_integration_service.h"
alemated70e82f2016-04-05 12:21:33268#include "chrome/browser/chromeos/login/test/js_checker.h"
Toni Barzicc45d9b12017-07-25 02:53:36269#include "chrome/browser/chromeos/note_taking_helper.h"
Alexander Hendrich55d0b0d92018-05-08 11:29:10270#include "chrome/browser/chromeos/policy/login_policy_test_base.h"
Alexander Hendrich9ce49262018-05-29 13:35:46271#include "chrome/browser/chromeos/policy/user_policy_test_helper.h"
Alexander Hendrich55d0b0d92018-05-08 11:29:10272#include "chrome/browser/chromeos/profiles/profile_helper.h"
alemated70e82f2016-04-05 12:21:33273#include "chrome/browser/chromeos/system/timezone_resolver_manager.h"
flackr149080062014-12-03 14:35:37274#include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
Elliot Glaysher685b3cd2018-02-01 23:17:55275#include "chrome/browser/ui/ash/chrome_screenshot_grabber_test_observer.h"
Steven Bennetts83149642018-12-06 01:47:29276#include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h"
[email protected]934e3c92013-08-01 00:18:23277#include "chromeos/audio/cras_audio_handler.h"
Sam McNally5edde0a2019-02-27 11:10:03278#include "chromeos/constants/chromeos_features.h"
Steven Bennetts38e9bde22019-01-03 17:31:10279#include "chromeos/constants/chromeos_switches.h"
alemated70e82f2016-04-05 12:21:33280#include "chromeos/cryptohome/cryptohome_parameters.h"
Alexander Alekseev3f09a8f2018-05-03 02:52:10281#include "components/account_id/account_id.h"
Hidehiko Abe33e9adf2017-09-13 06:12:23282#include "components/arc/arc_prefs.h"
hidehikoaab3dea2017-01-30 14:36:46283#include "components/arc/arc_util.h"
Yusuke Satod41a2c92019-03-26 00:55:14284#include "components/arc/session/arc_session_runner.h"
hidehiko88160c82016-10-18 09:43:47285#include "components/arc/test/fake_arc_session.h"
alemated70e82f2016-04-05 12:21:33286#include "components/user_manager/user_manager.h"
flackr149080062014-12-03 14:35:37287#include "ui/snapshot/screenshot_grabber.h"
[email protected]7ea48702012-09-03 20:41:06288#endif
289
[email protected]369d5a52013-09-18 10:09:53290#if !defined(OS_MACOSX)
[email protected]369d5a52013-09-18 10:09:53291#include "base/compiler_specific.h"
thestig53986dc2014-12-16 06:09:18292#include "chrome/browser/ui/extensions/app_launch_params.h"
[email protected]369d5a52013-09-18 10:09:53293#include "chrome/browser/ui/extensions/application_launch.h"
hashimotoad3c6872014-08-29 09:46:57294#include "extensions/browser/app_window/app_window.h"
295#include "extensions/browser/app_window/app_window_registry.h"
[email protected]2accabe2014-08-20 07:48:29296#include "extensions/browser/app_window/native_app_window.h"
[email protected]369d5a52013-09-18 10:09:53297#include "ui/base/window_open_disposition.h"
298#endif
299
Nick Petersond952cb772018-03-07 15:46:03300#if defined(OS_WIN)
301#include "base/win/win_util.h"
302#endif
303
Derek Cheng34478382018-04-07 00:32:59304#if !defined(OS_ANDROID)
305#include "chrome/browser/media/router/media_router_feature.h"
Greg Thompson146eef8c2018-06-26 09:30:54306#include "chrome/browser/profiles/profile_manager.h"
307#include "chrome/browser/ui/browser_finder.h"
308#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
Takumi Fujimoto906aab7c2019-02-22 22:11:16309#include "chrome/browser/ui/toolbar/media_router_action_controller.h"
Derek Cheng34478382018-04-07 00:32:59310#endif
311
[email protected]38a4db92012-08-29 09:36:05312using content::BrowserThread;
xunjieli0332c192014-09-10 23:23:31313using net::URLRequestMockHTTPJob;
Elad Alon39b1f6cc2018-08-30 09:52:21314using testing::_;
[email protected]9a8764b2013-03-27 16:18:09315using testing::Mock;
[email protected]3757c7d2012-07-23 11:24:36316using testing::Return;
Elad Alon39b1f6cc2018-08-30 09:52:21317using webrtc_event_logging::WebRtcEventLogManager;
[email protected]3757c7d2012-07-23 11:24:36318
319namespace policy {
320
[email protected]b561aab2012-08-27 20:17:49321namespace {
322
[email protected]8e0ba06b2013-10-28 15:38:09323#if defined(OS_CHROMEOS)
324const int kOneHourInMs = 60 * 60 * 1000;
325const int kThreeHoursInMs = 180 * 60 * 1000;
326#endif
327
[email protected]b561aab2012-08-27 20:17:49328const char kURL[] = "http://example.com";
329const char kCookieValue[] = "converted=true";
330// Assigned to Philip J. Fry to fix eventually.
maksim.sisov18b63ea2016-06-14 18:05:17331// TODO(maksims): use year 3000 when we get rid off the 32-bit
332// versions. https://crbug.com/619828
333const char kCookieOptions[] = ";expires=Wed Jan 01 2038 00:00:00 GMT";
[email protected]b561aab2012-08-27 20:17:49334
[email protected]650b2d52013-02-10 03:41:45335const base::FilePath::CharType kTestExtensionsDir[] =
336 FILE_PATH_LITERAL("extensions");
337const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
Devlin Cronin5e9387c32018-04-20 04:22:03338const base::FilePath::CharType kSimpleWithIconCrxName[] =
339 FILE_PATH_LITERAL("simple_with_icon.crx");
[email protected]650b2d52013-02-10 03:41:45340const base::FilePath::CharType kHostedAppCrxName[] =
[email protected]ce4e5d7a2012-12-11 20:59:26341 FILE_PATH_LITERAL("hosted_app.crx");
[email protected]ec29ec032012-09-10 18:27:09342
343const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
Devlin Cronin5e9387c32018-04-20 04:22:03344const char kSimpleWithIconCrxId[] = "dehdlahnlebladnfleagmjdapdjdcnlp";
[email protected]ce4e5d7a2012-12-11 20:59:26345const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
[email protected]ec29ec032012-09-10 18:27:09346
binjin8e3d0182014-12-04 16:44:28347const base::FilePath::CharType kGoodV1CrxName[] =
348 FILE_PATH_LITERAL("good_v1.crx");
Devlin Cronin19775cc2018-04-19 15:04:26349const base::FilePath::CharType kSimpleWithPopupExt[] =
350 FILE_PATH_LITERAL("simple_with_popup");
[email protected]ec1b3e712013-05-25 14:29:16351const base::FilePath::CharType kAppUnpackedExt[] =
352 FILE_PATH_LITERAL("app");
[email protected]095ccbe42013-09-26 00:06:42353
Becca Hughesfe8c32c2018-03-21 13:36:56354const char kAutoplayTestPageURL[] = "/media/autoplay_iframe.html";
355
[email protected]095ccbe42013-09-26 00:06:42356#if !defined(OS_MACOSX)
[email protected]369d5a52013-09-18 10:09:53357const base::FilePath::CharType kUnpackedFullscreenAppName[] =
358 FILE_PATH_LITERAL("fullscreen_app");
[email protected]095ccbe42013-09-26 00:06:42359#endif // !defined(OS_MACOSX)
[email protected]ec29ec032012-09-10 18:27:09360
guidouca055a542016-08-11 11:15:53361// Arbitrary port range for testing the WebRTC UDP port policy.
362const char kTestWebRtcUdpPortRange[] = "10000-10100";
guidouca055a542016-08-11 11:15:53363
Elad Alonbe6c2cf72018-09-05 13:24:51364constexpr size_t kWebAppId = 42;
365
Jun Caiaa248692017-11-10 20:10:51366void GetTestDataDirectory(base::FilePath* test_data_directory) {
Avi Drissman9098f9002018-05-04 00:11:52367 ASSERT_TRUE(
368 base::PathService::Get(chrome::DIR_TEST_DATA, test_data_directory));
Jun Caiaa248692017-11-10 20:10:51369}
370
Weilun Shib59ba592018-08-07 22:42:35371content::RenderFrameHost* GetMostVisitedIframe(content::WebContents* tab) {
372 for (content::RenderFrameHost* frame : tab->GetAllFrames()) {
373 if (frame->GetFrameName() == "mv-single")
374 return frame;
375 }
376 return nullptr;
377}
378
[email protected]38a4db92012-08-29 09:36:05379// Filters requests to the hosts in |urls| and redirects them to the test data
380// dir through URLRequestMockHTTPJobs.
[email protected]233b688e2012-11-27 10:44:12381void RedirectHostsToTestData(const char* const urls[], size_t size) {
[email protected]38a4db92012-08-29 09:36:05382 // Map the given hosts to the test data dir.
383 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
[email protected]650b2d52013-02-10 03:41:45384 base::FilePath base_path;
Jun Caiaa248692017-11-10 20:10:51385 GetTestDataDirectory(&base_path);
[email protected]38a4db92012-08-29 09:36:05386 for (size_t i = 0; i < size; ++i) {
[email protected]233b688e2012-11-27 10:44:12387 const GURL url(urls[i]);
388 EXPECT_TRUE(url.is_valid());
Gabriel Charettecf00b1082017-06-16 19:42:39389 filter->AddUrlInterceptor(
390 url, URLRequestMockHTTPJob::CreateInterceptor(base_path));
[email protected]f53b4802012-12-20 17:04:23391 }
392}
393
[email protected]d1208ba32012-11-08 11:10:33394// Fails requests using ERR_CONNECTION_RESET.
pauljensen754dde232015-06-03 05:47:29395class FailedJobInterceptor : public net::URLRequestInterceptor {
396 public:
397 FailedJobInterceptor() {}
398 ~FailedJobInterceptor() override {}
399
400 // URLRequestInterceptor implementation:
401 net::URLRequestJob* MaybeInterceptRequest(
402 net::URLRequest* request,
403 net::NetworkDelegate* network_delegate) const override {
404 return new net::URLRequestFailedJob(request, network_delegate,
405 net::ERR_CONNECTION_RESET);
406 }
407
408 private:
409 DISALLOW_COPY_AND_ASSIGN(FailedJobInterceptor);
410};
[email protected]d1208ba32012-11-08 11:10:33411
[email protected]f53b4802012-12-20 17:04:23412// While |MakeRequestFail| is in scope URLRequests to |host| will fail.
413class MakeRequestFail {
414 public:
415 // Sets up the filter on IO thread such that requests to |host| fail.
416 explicit MakeRequestFail(const std::string& host) : host_(host) {
Wezc0998d082018-07-06 17:50:18417 base::RunLoop run_loop;
Eric Seckler8652dcd52018-09-20 10:42:28418 base::PostTaskWithTraitsAndReply(FROM_HERE, {BrowserThread::IO},
419 base::BindOnce(MakeRequestFailOnIO, host_),
420 run_loop.QuitClosure());
Wezc0998d082018-07-06 17:50:18421 run_loop.Run();
[email protected]f53b4802012-12-20 17:04:23422 }
423 ~MakeRequestFail() {
Wezc0998d082018-07-06 17:50:18424 base::RunLoop run_loop;
Eric Seckler8652dcd52018-09-20 10:42:28425 base::PostTaskWithTraitsAndReply(
426 FROM_HERE, {BrowserThread::IO},
Wezc0998d082018-07-06 17:50:18427 base::BindOnce(UndoMakeRequestFailOnIO, host_), run_loop.QuitClosure());
428 run_loop.Run();
[email protected]f53b4802012-12-20 17:04:23429 }
[email protected]d1208ba32012-11-08 11:10:33430
[email protected]f53b4802012-12-20 17:04:23431 private:
432 // Filters requests to the |host| such that they fail. Run on IO thread.
433 static void MakeRequestFailOnIO(const std::string& host) {
434 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
dcheng08cfe9ba2016-04-14 17:46:45435 filter->AddHostnameInterceptor("http", host,
436 std::unique_ptr<net::URLRequestInterceptor>(
437 new FailedJobInterceptor()));
438 filter->AddHostnameInterceptor("https", host,
439 std::unique_ptr<net::URLRequestInterceptor>(
440 new FailedJobInterceptor()));
[email protected]f53b4802012-12-20 17:04:23441 }
442
443 // Remove filters for requests to the |host|. Run on IO thread.
444 static void UndoMakeRequestFailOnIO(const std::string& host) {
445 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
446 filter->RemoveHostnameHandler("http", host);
447 filter->RemoveHostnameHandler("https", host);
448 }
449
450 const std::string host_;
451};
[email protected]d1208ba32012-11-08 11:10:33452
Yuzhu Shenf3c2fcc2017-11-30 20:30:22453// Registers a handler to respond to requests whose path matches |match_path|.
454// The response contents are generated from |template_file|, by replacing all
455// "${URL_PLACEHOLDER}" substrings in the file with the request URL excluding
456// filename, query values and fragment.
457void RegisterURLReplacingHandler(net::EmbeddedTestServer* test_server,
458 const std::string& match_path,
459 const base::FilePath& template_file) {
460 test_server->RegisterRequestHandler(base::Bind(
461 [](net::EmbeddedTestServer* test_server, const std::string& match_path,
462 const base::FilePath& template_file,
463 const net::test_server::HttpRequest& request)
464 -> std::unique_ptr<net::test_server::HttpResponse> {
465 GURL url = test_server->GetURL(request.relative_url);
466 if (url.path() != match_path)
467 return nullptr;
468
469 std::string contents;
470 CHECK(base::ReadFileToString(template_file, &contents));
471
472 GURL url_base = url.GetWithoutFilename();
473 base::ReplaceSubstringsAfterOffset(&contents, 0, "${URL_PLACEHOLDER}",
474 url_base.spec());
475
476 auto response = std::make_unique<net::test_server::BasicHttpResponse>();
477 response->set_content(contents);
478 response->set_content_type("text/plain");
479 return response;
480 },
481 base::Unretained(test_server), match_path, template_file));
482}
483
[email protected]233b688e2012-11-27 10:44:12484// Verifies that the given url |spec| can be opened. This assumes that |spec|
485// points at empty.html in the test data dir.
Yuzhu Shen6ccfd562017-10-27 16:38:18486void CheckCanOpenURL(Browser* browser, const std::string& spec) {
[email protected]233b688e2012-11-27 10:44:12487 GURL url(spec);
[email protected]38a4db92012-08-29 09:36:05488 ui_test_utils::NavigateToURL(browser, url);
[email protected]617ee962013-01-29 20:49:12489 content::WebContents* contents =
490 browser->tab_strip_model()->GetActiveWebContents();
jamd6be16e2014-09-28 15:18:34491 EXPECT_EQ(url, contents->GetURL());
edwardjunge76b5802016-08-11 13:38:48492
493 base::string16 blocked_page_title;
494 if (url.has_host()) {
495 blocked_page_title = base::UTF8ToUTF16(url.host());
496 } else {
497 // Local file paths show the full URL.
498 blocked_page_title = base::UTF8ToUTF16(url.spec());
499 }
500 EXPECT_NE(blocked_page_title, contents->GetTitle());
[email protected]38a4db92012-08-29 09:36:05501}
502
[email protected]233b688e2012-11-27 10:44:12503// Verifies that access to the given url |spec| is blocked.
Greg Thompson2f011a452018-04-30 09:44:14504void CheckURLIsBlockedInWebContents(content::WebContents* web_contents,
505 const GURL& url) {
506 EXPECT_EQ(url, web_contents->GetURL());
edwardjunge76b5802016-08-11 13:38:48507
508 base::string16 blocked_page_title;
509 if (url.has_host()) {
510 blocked_page_title = base::UTF8ToUTF16(url.host());
511 } else {
512 // Local file paths show the full URL.
513 blocked_page_title = base::UTF8ToUTF16(url.spec());
514 }
Greg Thompson2f011a452018-04-30 09:44:14515 EXPECT_EQ(blocked_page_title, web_contents->GetTitle());
[email protected]38a4db92012-08-29 09:36:05516
517 // Verify that the expected error page is being displayed.
[email protected]38a4db92012-08-29 09:36:05518 bool result = false;
jamd6be16e2014-09-28 15:18:34519 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
Greg Thompson2f011a452018-04-30 09:44:14520 web_contents,
[email protected]71caef02013-03-25 17:40:20521 "var textContent = document.body.textContent;"
522 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
[email protected]06bc5d92013-01-02 22:44:13523 "domAutomationController.send(hasError);",
[email protected]38a4db92012-08-29 09:36:05524 &result));
jamd6be16e2014-09-28 15:18:34525 EXPECT_TRUE(result);
[email protected]38a4db92012-08-29 09:36:05526}
527
Greg Thompson2f011a452018-04-30 09:44:14528// Verifies that access to the given url |spec| is blocked.
529void CheckURLIsBlocked(Browser* browser, const std::string& spec) {
530 GURL url(spec);
531 ui_test_utils::NavigateToURL(browser, url);
532 content::WebContents* contents =
533 browser->tab_strip_model()->GetActiveWebContents();
534 CheckURLIsBlockedInWebContents(contents, url);
535}
536
[email protected]d1251212012-08-29 13:15:59537// Downloads a file named |file| and expects it to be saved to |dir|, which
538// must be empty.
Mattias Nissler441cc652018-04-05 00:08:56539void DownloadAndVerifyFile(Browser* browser,
540 const base::FilePath& dir,
541 const base::FilePath& file) {
Jun Caiaa248692017-11-10 20:10:51542 net::EmbeddedTestServer embedded_test_server;
543 base::FilePath test_data_directory;
544 GetTestDataDirectory(&test_data_directory);
545 embedded_test_server.ServeFilesFromDirectory(test_data_directory);
546 ASSERT_TRUE(embedded_test_server.Start());
[email protected]d1251212012-08-29 13:15:59547 content::DownloadManager* download_manager =
548 content::BrowserContext::GetDownloadManager(browser->profile());
549 content::DownloadTestObserverTerminal observer(
550 download_manager, 1,
551 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
Jun Caiaa248692017-11-10 20:10:51552 GURL url(embedded_test_server.GetURL("/" + file.MaybeAsASCII()));
[email protected]650b2d52013-02-10 03:41:45553 base::FilePath downloaded = dir.Append(file);
[email protected]7567484142013-07-11 17:36:07554 EXPECT_FALSE(base::PathExists(downloaded));
thestig53986dc2014-12-16 06:09:18555 ui_test_utils::NavigateToURL(browser, url);
[email protected]d1251212012-08-29 13:15:59556 observer.WaitForFinished();
Min Qina9f487872018-02-09 20:43:23557 EXPECT_EQ(1u,
558 observer.NumDownloadsSeenInState(download::DownloadItem::COMPLETE));
[email protected]7567484142013-07-11 17:36:07559 EXPECT_TRUE(base::PathExists(downloaded));
[email protected]25a4c1c2013-06-08 04:53:36560 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
[email protected]d1251212012-08-29 13:15:59561 EXPECT_EQ(file, enumerator.Next().BaseName());
[email protected]650b2d52013-02-10 03:41:45562 EXPECT_EQ(base::FilePath(), enumerator.Next());
[email protected]d1251212012-08-29 13:15:59563}
564
[email protected]81198da52014-03-19 10:45:20565#if defined(OS_CHROMEOS)
[email protected]7ea48702012-09-03 20:41:06566int CountScreenshots() {
567 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
[email protected]82f5bf32013-12-23 00:22:00568 ProfileManager::GetActiveUserProfile());
[email protected]25a4c1c2013-06-08 04:53:36569 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
570 false, base::FileEnumerator::FILES,
571 "Screenshot*");
[email protected]7ea48702012-09-03 20:41:06572 int count = 0;
573 while (!enumerator.Next().empty())
574 count++;
575 return count;
576}
577#endif
578
[email protected]bb34f262012-09-05 09:09:46579// Checks if WebGL is enabled in the given WebContents.
580bool IsWebGLEnabled(content::WebContents* contents) {
581 bool result = false;
[email protected]b6987e02013-01-04 18:30:43582 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
583 contents,
[email protected]06bc5d92013-01-02 22:44:13584 "var canvas = document.createElement('canvas');"
[email protected]fb315ea2013-11-14 16:23:52585 "var context = canvas.getContext('webgl');"
[email protected]06bc5d92013-01-02 22:44:13586 "domAutomationController.send(context != null);",
[email protected]bb34f262012-09-05 09:09:46587 &result));
588 return result;
589}
590
[email protected]ea826362012-09-05 23:31:37591bool IsJavascriptEnabled(content::WebContents* contents) {
Avi Drissman3d8c65a2019-03-19 22:14:07592 base::Value value =
dcheng08cfe9ba2016-04-14 17:46:45593 content::ExecuteScriptAndGetValue(contents->GetMainFrame(), "123");
Avi Drissman3d8c65a2019-03-19 22:14:07594 return value.is_int() && value.GetInt() == 123;
[email protected]ea826362012-09-05 23:31:37595}
596
[email protected]27ef988d2014-08-01 17:00:40597bool IsNetworkPredictionEnabled(PrefService* prefs) {
gabadie85b991d2016-01-07 10:39:39598 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs) ==
599 chrome_browser_net::NetworkPredictionStatus::ENABLED;
[email protected]27ef988d2014-08-01 17:00:40600}
601
[email protected]307aec72012-09-18 21:52:44602void FlushBlacklistPolicy() {
603 // Updates of the URLBlacklist are done on IO, after building the blacklist
joaodasilva8d2d9252014-09-01 14:41:24604 // on the blocking pool, which is initiated from IO.
[email protected]307aec72012-09-18 21:52:44605 content::RunAllPendingInMessageLoop(BrowserThread::IO);
Gabriel Charette01507a22017-09-27 21:30:08606 content::RunAllTasksUntilIdle();
[email protected]307aec72012-09-18 21:52:44607 content::RunAllPendingInMessageLoop(BrowserThread::IO);
608}
609
[email protected]f6c14732013-02-25 19:09:20610bool ContainsVisibleElement(content::WebContents* contents,
611 const std::string& id) {
612 bool result;
613 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
614 contents,
615 "var elem = document.getElementById('" + id + "');"
[email protected]7bc0c96622013-03-27 15:36:10616 "domAutomationController.send(!!elem && !elem.hidden);",
[email protected]f6c14732013-02-25 19:09:20617 &result));
618 return result;
619}
620
Weilun Shib59ba592018-08-07 22:42:35621bool ContainsWebstoreTile(content::RenderFrameHost* iframe) {
622 int num_webstore_tiles = 0;
623 EXPECT_TRUE(instant_test_utils::GetIntFromJS(
624 iframe,
625 "document.querySelectorAll(\".md-tile[href='" +
626 l10n_util::GetStringUTF8(IDS_WEBSTORE_URL) + "']\").length",
627 &num_webstore_tiles));
628 return num_webstore_tiles == 1;
629}
630
[email protected]6af5e302012-09-20 19:29:09631#if defined(OS_CHROMEOS)
[email protected]934e3c92013-08-01 00:18:23632class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
[email protected]6af5e302012-09-20 19:29:09633 public:
[email protected]934e3c92013-08-01 00:18:23634 TestAudioObserver() : output_mute_changed_count_(0) {
635 }
[email protected]6af5e302012-09-20 19:29:09636
[email protected]934e3c92013-08-01 00:18:23637 int output_mute_changed_count() const {
638 return output_mute_changed_count_;
639 }
640
dcheng6d888df2015-01-16 18:12:48641 ~TestAudioObserver() override {}
[email protected]934e3c92013-08-01 00:18:23642
643 protected:
644 // chromeos::CrasAudioHandler::AudioObserver overrides.
Evan Stade5a226fb2019-03-18 17:02:12645 void OnOutputMuteChanged(bool /* mute_on */) override {
jennyz170e7fb2015-03-30 23:37:39646 ++output_mute_changed_count_;
647 }
[email protected]6af5e302012-09-20 19:29:09648
649 private:
[email protected]934e3c92013-08-01 00:18:23650 int output_mute_changed_count_;
651
652 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
[email protected]6af5e302012-09-20 19:29:09653};
654#endif
655
[email protected]1eb39642013-10-17 22:06:53656// This class waits until either a load stops or the WebContents is destroyed.
657class WebContentsLoadedOrDestroyedWatcher
658 : public content::WebContentsObserver {
[email protected]6b9dafc2013-08-30 15:41:59659 public:
[email protected]1eb39642013-10-17 22:06:53660 explicit WebContentsLoadedOrDestroyedWatcher(
661 content::WebContents* web_contents);
dcheng32ae6bbb2014-10-22 08:47:29662 ~WebContentsLoadedOrDestroyedWatcher() override;
[email protected]6b9dafc2013-08-30 15:41:59663
[email protected]1eb39642013-10-17 22:06:53664 // Waits until the WebContents's load is done or until it is destroyed.
[email protected]6b9dafc2013-08-30 15:41:59665 void Wait();
666
[email protected]1eb39642013-10-17 22:06:53667 // Overridden WebContentsObserver methods.
dcheng32ae6bbb2014-10-22 08:47:29668 void WebContentsDestroyed() override;
fdegans6ce28f52015-03-19 12:52:22669 void DidStopLoading() override;
[email protected]6b9dafc2013-08-30 15:41:59670
671 private:
[email protected]6b9dafc2013-08-30 15:41:59672 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
673
[email protected]1eb39642013-10-17 22:06:53674 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
[email protected]6b9dafc2013-08-30 15:41:59675};
676
[email protected]1eb39642013-10-17 22:06:53677WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
678 content::WebContents* web_contents)
679 : content::WebContentsObserver(web_contents),
680 message_loop_runner_(new content::MessageLoopRunner) {
[email protected]6b9dafc2013-08-30 15:41:59681}
682
[email protected]1eb39642013-10-17 22:06:53683WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
[email protected]6b9dafc2013-08-30 15:41:59684
[email protected]1eb39642013-10-17 22:06:53685void WebContentsLoadedOrDestroyedWatcher::Wait() {
[email protected]6b9dafc2013-08-30 15:41:59686 message_loop_runner_->Run();
[email protected]6b9dafc2013-08-30 15:41:59687}
688
[email protected]12a46832014-05-09 13:35:58689void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
[email protected]6b9dafc2013-08-30 15:41:59690 message_loop_runner_->Quit();
[email protected]1eb39642013-10-17 22:06:53691}
692
fdegans6ce28f52015-03-19 12:52:22693void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
[email protected]1eb39642013-10-17 22:06:53694 message_loop_runner_->Quit();
[email protected]6b9dafc2013-08-30 15:41:59695}
696
[email protected]369d5a52013-09-18 10:09:53697#if !defined(OS_MACOSX)
698
[email protected]dbb03fb2014-02-15 05:36:33699// Observer used to wait for the creation of a new app window.
hashimotoad3c6872014-08-29 09:46:57700class TestAddAppWindowObserver
701 : public extensions::AppWindowRegistry::Observer {
[email protected]369d5a52013-09-18 10:09:53702 public:
hashimotoad3c6872014-08-29 09:46:57703 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
dchenge1bc7982014-10-30 00:32:40704 ~TestAddAppWindowObserver() override;
[email protected]369d5a52013-09-18 10:09:53705
hashimotoad3c6872014-08-29 09:46:57706 // extensions::AppWindowRegistry::Observer:
dchenge1bc7982014-10-30 00:32:40707 void OnAppWindowAdded(extensions::AppWindow* app_window) override;
[email protected]369d5a52013-09-18 10:09:53708
hashimotoad3c6872014-08-29 09:46:57709 extensions::AppWindow* WaitForAppWindow();
[email protected]369d5a52013-09-18 10:09:53710
711 private:
hashimotoad3c6872014-08-29 09:46:57712 extensions::AppWindowRegistry* registry_; // Not owned.
713 extensions::AppWindow* window_; // Not owned.
[email protected]369d5a52013-09-18 10:09:53714 base::RunLoop run_loop_;
715
[email protected]dbb03fb2014-02-15 05:36:33716 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
[email protected]369d5a52013-09-18 10:09:53717};
718
[email protected]dbb03fb2014-02-15 05:36:33719TestAddAppWindowObserver::TestAddAppWindowObserver(
hashimotoad3c6872014-08-29 09:46:57720 extensions::AppWindowRegistry* registry)
[email protected]dbb03fb2014-02-15 05:36:33721 : registry_(registry), window_(NULL) {
[email protected]369d5a52013-09-18 10:09:53722 registry_->AddObserver(this);
723}
724
[email protected]dbb03fb2014-02-15 05:36:33725TestAddAppWindowObserver::~TestAddAppWindowObserver() {
[email protected]369d5a52013-09-18 10:09:53726 registry_->RemoveObserver(this);
727}
728
hashimotoad3c6872014-08-29 09:46:57729void TestAddAppWindowObserver::OnAppWindowAdded(
730 extensions::AppWindow* app_window) {
[email protected]dbb03fb2014-02-15 05:36:33731 window_ = app_window;
[email protected]369d5a52013-09-18 10:09:53732 run_loop_.Quit();
733}
734
hashimotoad3c6872014-08-29 09:46:57735extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
[email protected]369d5a52013-09-18 10:09:53736 run_loop_.Run();
737 return window_;
738}
739
740#endif
741
Michael Giuffrida9e1a9f82017-08-08 14:23:29742#if !defined(OS_CHROMEOS)
743extensions::MessagingDelegate::PolicyPermission IsNativeMessagingHostAllowed(
744 content::BrowserContext* browser_context,
745 const std::string& native_host_name) {
746 extensions::MessagingDelegate* messaging_delegate =
747 extensions::ExtensionsAPIClient::Get()->GetMessagingDelegate();
748 EXPECT_NE(messaging_delegate, nullptr);
749 return messaging_delegate->IsNativeMessagingHostAllowed(browser_context,
750 native_host_name);
751}
752#endif
753
Jialiu Lin4d7c6042018-04-04 17:45:35754class MockPasswordProtectionService
755 : public safe_browsing::ChromePasswordProtectionService {
756 public:
757 MockPasswordProtectionService(safe_browsing::SafeBrowsingService* sb_service,
758 Profile* profile)
759 : safe_browsing::ChromePasswordProtectionService(sb_service, profile) {}
760 ~MockPasswordProtectionService() override {}
761
762 MOCK_CONST_METHOD0(GetSyncAccountType,
763 safe_browsing::LoginReputationClientRequest::
764 PasswordReuseEvent::SyncAccountType());
765
766 AccountInfo GetAccountInfo() const override {
767 AccountInfo info;
768 info.email = "[email protected]";
769 return info;
770 }
771};
772
[email protected]b561aab2012-08-27 20:17:49773} // namespace
774
[email protected]3757c7d2012-07-23 11:24:36775class PolicyTest : public InProcessBrowserTest {
776 protected:
777 PolicyTest() {}
dchenge1bc7982014-10-30 00:32:40778 ~PolicyTest() override {}
[email protected]3757c7d2012-07-23 11:24:36779
dchenge1bc7982014-10-30 00:32:40780 void SetUp() override {
[email protected]044e86992014-01-24 22:59:11781 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
782 InProcessBrowserTest::SetUp();
783 }
784
dcheng32ae6bbb2014-10-22 08:47:29785 void SetUpInProcessBrowserTestFixture() override {
avi556c05022014-12-22 23:31:43786 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
[email protected]49d5d422013-01-31 15:50:49787 EXPECT_CALL(provider_, IsInitializationComplete(_))
[email protected]3757c7d2012-07-23 11:24:36788 .WillRepeatedly(Return(true));
789 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
790 }
791
dcheng32ae6bbb2014-10-22 08:47:29792 void SetUpOnMainThread() override {
Yuzhu Shen6ccfd562017-10-27 16:38:18793 host_resolver()->AddRule("*", "127.0.0.1");
rockotffa65b12014-10-14 17:19:06794 if (extension_service()->updater()) {
795 extension_service()->updater()->SetExtensionCacheForTesting(
796 test_extension_cache_.get());
797 }
[email protected]38a4db92012-08-29 09:36:05798 }
799
Carlos IL5a9e7512019-06-13 22:35:28800 void SetUpCommandLine(base::CommandLine* command_line) override {
801 variations::testing::VariationParamsManager::AppendVariationParams(
802 "ReportCertificateErrors", "ShowAndPossiblySend",
803 {{"sendingThreshold", "1.0"}}, command_line);
804 }
805
[email protected]7ea48702012-09-03 20:41:06806 void SetScreenshotPolicy(bool enabled) {
807 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:09808 policies.Set(key::kDisableScreenshots, POLICY_LEVEL_MANDATORY,
809 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:30810 std::make_unique<base::Value>(!enabled), nullptr);
[email protected]161245d2013-01-09 14:28:11811 UpdateProviderPolicy(policies);
[email protected]7ea48702012-09-03 20:41:06812 }
813
Doug Turner9e79cf0c2018-04-05 21:32:30814 void SetShouldRequireCTForTesting(bool* required) {
Clark DuVall8c88d4ef02018-11-30 01:45:16815 if (content::IsOutOfProcessNetworkService()) {
Doug Turner9e79cf0c2018-04-05 21:32:30816 network::mojom::NetworkServiceTestPtr network_service_test;
Ken Rockoteff2b822019-06-20 22:56:53817 content::GetSystemConnector()->BindInterface(
818 content::mojom::kNetworkServiceName, &network_service_test);
Doug Turner9e79cf0c2018-04-05 21:32:30819 network::mojom::NetworkServiceTest::ShouldRequireCT required_ct;
820 if (!required) {
821 required_ct =
822 network::mojom::NetworkServiceTest::ShouldRequireCT::RESET;
823 } else {
824 required_ct =
825 *required
826 ? network::mojom::NetworkServiceTest::ShouldRequireCT::REQUIRE
827 : network::mojom::NetworkServiceTest::ShouldRequireCT::
828 DONT_REQUIRE;
829 }
830
831 mojo::ScopedAllowSyncCallForTesting allow_sync_call;
832 network_service_test->SetShouldRequireCT(required_ct);
833 return;
834 }
835
Eric Seckler8652dcd52018-09-20 10:42:28836 base::PostTaskWithTraits(
837 FROM_HERE, {BrowserThread::IO},
Doug Turner9e79cf0c2018-04-05 21:32:30838 base::BindOnce(
839 &net::TransportSecurityState::SetShouldRequireCTForTesting,
840 required));
841 }
842
[email protected]7ea48702012-09-03 20:41:06843#if defined(OS_CHROMEOS)
Elliot Glaysher685b3cd2018-02-01 23:17:55844 class QuitMessageLoopAfterScreenshot
845 : public ChromeScreenshotGrabberTestObserver {
[email protected]24e4cac2014-01-15 09:54:59846 public:
Wezc0998d082018-07-06 17:50:18847 explicit QuitMessageLoopAfterScreenshot(base::OnceClosure done)
848 : done_(std::move(done)) {}
dcheng6d888df2015-01-16 18:12:48849 void OnScreenshotCompleted(
Elliot Glaysher685b3cd2018-02-01 23:17:55850 ui::ScreenshotResult screenshot_result,
mostynb2b52d1db2014-10-07 02:47:17851 const base::FilePath& screenshot_path) override {
Eric Seckler8652dcd52018-09-20 10:42:28852 base::PostTaskWithTraitsAndReply(FROM_HERE, {BrowserThread::IO},
853 base::DoNothing(), std::move(done_));
[email protected]24e4cac2014-01-15 09:54:59854 }
855
dcheng6d888df2015-01-16 18:12:48856 ~QuitMessageLoopAfterScreenshot() override {}
Wezc0998d082018-07-06 17:50:18857
858 private:
859 base::OnceClosure done_;
[email protected]24e4cac2014-01-15 09:54:59860 };
861
[email protected]7ea48702012-09-03 20:41:06862 void TestScreenshotFile(bool enabled) {
Wezc0998d082018-07-06 17:50:18863 base::RunLoop run_loop;
864 QuitMessageLoopAfterScreenshot observer_(run_loop.QuitClosure());
865
James Cook5e9d3402017-11-01 00:20:12866 ChromeScreenshotGrabber* grabber = ChromeScreenshotGrabber::Get();
Elliot Glaysher685b3cd2018-02-01 23:17:55867 grabber->test_observer_ = &observer_;
[email protected]7ea48702012-09-03 20:41:06868 SetScreenshotPolicy(enabled);
James Cook5e9d3402017-11-01 00:20:12869 grabber->HandleTakeScreenshotForAllRootWindows();
Wezc0998d082018-07-06 17:50:18870 run_loop.Run();
871
Elliot Glaysher685b3cd2018-02-01 23:17:55872 grabber->test_observer_ = nullptr;
[email protected]7ea48702012-09-03 20:41:06873 }
James Cook5e9d3402017-11-01 00:20:12874#endif // defined(OS_CHROMEOS)
[email protected]7ea48702012-09-03 20:41:06875
Devlin Cronin2824e9c2018-06-01 23:32:05876 extensions::ExtensionService* extension_service() {
[email protected]ec29ec032012-09-10 18:27:09877 extensions::ExtensionSystem* system =
878 extensions::ExtensionSystem::Get(browser()->profile());
879 return system->extension_service();
880 }
881
882 const extensions::Extension* InstallExtension(
[email protected]650b2d52013-02-10 03:41:45883 const base::FilePath::StringType& name) {
884 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
885 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
[email protected]ec29ec032012-09-10 18:27:09886 scoped_refptr<extensions::CrxInstaller> installer =
[email protected]f8636f92013-08-09 21:02:37887 extensions::CrxInstaller::CreateSilent(extension_service());
[email protected]ec29ec032012-09-10 18:27:09888 installer->set_allow_silent_install(true);
889 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
890 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
Joshua Pawlickifd01b7c2019-01-17 16:18:34891 installer->set_off_store_install_allow_reason(
892 extensions::CrxInstaller::OffStoreInstallAllowReason::
893 OffStoreInstallAllowedInTest);
[email protected]ec29ec032012-09-10 18:27:09894
895 content::WindowedNotificationObserver observer(
[email protected]adf5a102014-07-31 12:44:06896 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
[email protected]ec29ec032012-09-10 18:27:09897 content::NotificationService::AllSources());
898 installer->InstallCrx(extension_path);
899 observer.Wait();
900 content::Details<const extensions::Extension> details = observer.details();
901 return details.ptr();
902 }
903
Christopher Lam96b044c2017-11-24 03:29:46904 const extensions::Extension* InstallBookmarkApp() {
905 WebApplicationInfo web_app;
906 web_app.title = base::ASCIIToUTF16("Bookmark App");
907 web_app.app_url = GURL("http://www.google.com");
908
909 scoped_refptr<extensions::CrxInstaller> installer =
910 extensions::CrxInstaller::CreateSilent(extension_service());
911
912 content::WindowedNotificationObserver observer(
913 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
914 content::NotificationService::AllSources());
915 installer->InstallWebApp(web_app);
916 observer.Wait();
917 content::Details<const extensions::Extension> details = observer.details();
918 return details.ptr();
919 }
920
limasdfc83e0b72017-03-03 17:08:35921 scoped_refptr<const extensions::Extension> LoadUnpackedExtension(
922 const base::FilePath::StringType& name) {
[email protected]ec1b3e712013-05-25 14:29:16923 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
924 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
limasdfc83e0b72017-03-03 17:08:35925 extensions::ChromeTestExtensionLoader loader(browser()->profile());
926 return loader.LoadExtension(extension_path);
[email protected]ec1b3e712013-05-25 14:29:16927 }
928
[email protected]ec29ec032012-09-10 18:27:09929 void UninstallExtension(const std::string& id, bool expect_success) {
limasdf6ab4c2f2015-03-31 16:19:54930 if (expect_success) {
931 extensions::TestExtensionRegistryObserver observer(
932 extensions::ExtensionRegistry::Get(browser()->profile()));
933 extension_service()->UninstallExtension(
Devlin Cronin218df7f2017-11-21 21:41:31934 id, extensions::UNINSTALL_REASON_FOR_TESTING, NULL);
limasdf6ab4c2f2015-03-31 16:19:54935 observer.WaitForExtensionUninstalled();
936 } else {
937 content::WindowedNotificationObserver observer(
938 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
939 content::NotificationService::AllSources());
940 extension_service()->UninstallExtension(
941 id,
942 extensions::UNINSTALL_REASON_FOR_TESTING,
limasdf6ab4c2f2015-03-31 16:19:54943 NULL);
944 observer.Wait();
945 }
[email protected]ec29ec032012-09-10 18:27:09946 }
947
binjincccacef2014-10-13 19:00:20948 void DisableExtension(const std::string& id) {
limasdf6ab4c2f2015-03-31 16:19:54949 extensions::TestExtensionRegistryObserver observer(
950 extensions::ExtensionRegistry::Get(browser()->profile()));
Minh X. Nguyen45479012017-08-18 21:35:36951 extension_service()->DisableExtension(
Michael Giuffridab16cab32017-10-04 21:56:09952 id, extensions::disable_reason::DISABLE_USER_ACTION);
limasdf6ab4c2f2015-03-31 16:19:54953 observer.WaitForExtensionUnloaded();
binjincccacef2014-10-13 19:00:20954 }
955
[email protected]161245d2013-01-09 14:28:11956 void UpdateProviderPolicy(const PolicyMap& policy) {
Bartosz Fabianowski0248c492018-07-02 13:44:32957 PolicyMap policy_with_defaults;
958 policy_with_defaults.CopyFrom(policy);
959#if defined(OS_CHROMEOS)
960 SetEnterpriseUsersDefaults(&policy_with_defaults);
961#endif
962 provider_.UpdateChromePolicy(policy_with_defaults);
Gabriel Charettebbb7d2f2018-04-24 07:58:06963 DCHECK(base::MessageLoopCurrent::Get());
[email protected]161245d2013-01-09 14:28:11964 base::RunLoop loop;
965 loop.RunUntilIdle();
966 }
967
[email protected]8967816d2013-03-26 12:58:25968 // Sends a mouse click at the given coordinates to the current renderer.
969 void PerformClick(int x, int y) {
970 content::WebContents* contents =
971 browser()->tab_strip_model()->GetActiveWebContents();
Blink Reformat1c4d759e2017-04-09 16:34:54972 blink::WebMouseEvent click_event(
973 blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers,
Daniel Cheng93c80a92018-02-14 19:02:43974 blink::WebInputEvent::GetStaticTimeStampForTests());
Blink Reformat1c4d759e2017-04-09 16:34:54975 click_event.button = blink::WebMouseEvent::Button::kLeft;
976 click_event.click_count = 1;
977 click_event.SetPositionInWidget(x, y);
avif9ab5d942015-10-15 14:05:44978 contents->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(click_event);
Blink Reformat1c4d759e2017-04-09 16:34:54979 click_event.SetType(blink::WebInputEvent::kMouseUp);
avif9ab5d942015-10-15 14:05:44980 contents->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(click_event);
[email protected]8967816d2013-03-26 12:58:25981 }
982
dcheng3b344bc22016-05-10 02:26:09983 void SetPolicy(PolicyMap* policies,
984 const char* key,
985 std::unique_ptr<base::Value> value) {
treib2b188052015-04-17 12:32:50986 if (value) {
dcheng3b344bc22016-05-10 02:26:09987 policies->Set(key, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
988 POLICY_SOURCE_CLOUD, std::move(value), nullptr);
treib2b188052015-04-17 12:32:50989 } else {
990 policies->Erase(key);
991 }
992 }
993
jdoerrie239723572017-03-02 12:09:19994 void ApplySafeSearchPolicy(std::unique_ptr<base::Value> legacy_safe_search,
995 std::unique_ptr<base::Value> google_safe_search,
996 std::unique_ptr<base::Value> legacy_youtube,
997 std::unique_ptr<base::Value> youtube_restrict) {
treib2b188052015-04-17 12:32:50998 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:09999 SetPolicy(&policies, key::kForceSafeSearch, std::move(legacy_safe_search));
1000 SetPolicy(&policies, key::kForceGoogleSafeSearch,
1001 std::move(google_safe_search));
1002 SetPolicy(&policies, key::kForceYouTubeSafetyMode,
ljusten98684cb72016-10-11 13:26:181003 std::move(legacy_youtube));
1004 SetPolicy(&policies, key::kForceYouTubeRestrict,
1005 std::move(youtube_restrict));
treib2b188052015-04-17 12:32:501006 UpdateProviderPolicy(policies);
1007 }
1008
Steven Bennetts34692a332018-11-10 02:11:441009#if defined(OS_CHROMEOS)
Darren Shen8604a212019-06-07 00:41:381010 void SetEnableFlag(const keyboard::KeyboardEnableFlag& flag) {
Steven Bennetts34692a332018-11-10 02:11:441011 auto* keyboard_client = ChromeKeyboardControllerClient::Get();
1012 keyboard_client->SetEnableFlag(flag);
Steven Bennetts34692a332018-11-10 02:11:441013 }
1014
Darren Shen8604a212019-06-07 00:41:381015 void ClearEnableFlag(const keyboard::KeyboardEnableFlag& flag) {
Steven Bennetts34692a332018-11-10 02:11:441016 auto* keyboard_client = ChromeKeyboardControllerClient::Get();
1017 keyboard_client->ClearEnableFlag(flag);
Steven Bennetts34692a332018-11-10 02:11:441018 }
1019#endif
1020
John Abd-El-Malek9fb60492018-08-02 04:28:501021 static GURL GetExpectedSearchURL(bool expect_safe_search) {
1022 std::string expected_url("http://google.com/");
1023 if (expect_safe_search) {
1024 expected_url += "?" +
1025 std::string(safe_search_util::kSafeSearchSafeParameter) +
1026 "&" + safe_search_util::kSafeSearchSsuiParameter;
1027 }
1028 return GURL(expected_url);
1029 }
1030
John Abd-El-Malekd2b62ee2018-11-20 07:43:341031 static void CheckSafeSearch(Browser* browser,
1032 bool expect_safe_search,
1033 const std::string& url = "http://google.com/") {
treib2b188052015-04-17 12:32:501034 content::WebContents* web_contents =
John Abd-El-Malek9fb60492018-08-02 04:28:501035 browser->tab_strip_model()->GetActiveWebContents();
treib2b188052015-04-17 12:32:501036 content::TestNavigationObserver observer(web_contents);
Evan Stadead9765ab2019-07-02 17:02:411037 ui_test_utils::SendToOmniboxAndSubmit(browser, url);
treib2b188052015-04-17 12:32:501038 observer.Wait();
Evan Stadead9765ab2019-07-02 17:02:411039 OmniboxEditModel* model =
1040 browser->window()->GetLocationBar()->GetOmniboxView()->model();
treib2b188052015-04-17 12:32:501041 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
John Abd-El-Malek9fb60492018-08-02 04:28:501042 EXPECT_EQ(GetExpectedSearchURL(expect_safe_search), web_contents->GetURL());
1043 }
treib2b188052015-04-17 12:32:501044
John Abd-El-Malek9fb60492018-08-02 04:28:501045 static void CheckYouTubeRestricted(
1046 int youtube_restrict_mode,
1047 const std::map<GURL, net::HttpRequestHeaders>& urls_requested,
1048 const GURL& url) {
1049 auto iter = urls_requested.find(url);
1050 ASSERT_TRUE(iter != urls_requested.end());
1051 std::string header;
1052 iter->second.GetHeader(safe_search_util::kYouTubeRestrictHeaderName,
1053 &header);
1054 if (youtube_restrict_mode == safe_search_util::YOUTUBE_RESTRICT_OFF) {
1055 EXPECT_TRUE(header.empty());
1056 } else if (youtube_restrict_mode ==
1057 safe_search_util::YOUTUBE_RESTRICT_MODERATE) {
1058 EXPECT_EQ(header, safe_search_util::kYouTubeRestrictHeaderValueModerate);
1059 } else if (youtube_restrict_mode ==
1060 safe_search_util::YOUTUBE_RESTRICT_STRICT) {
1061 EXPECT_EQ(header, safe_search_util::kYouTubeRestrictHeaderValueStrict);
treib2b188052015-04-17 12:32:501062 }
John Abd-El-Malek9fb60492018-08-02 04:28:501063 }
1064
1065 static void CheckAllowedDomainsHeader(
1066 const std::string& allowed_domain,
1067 const std::map<GURL, net::HttpRequestHeaders>& urls_requested,
1068 const GURL& url) {
1069 auto iter = urls_requested.find(url);
1070 ASSERT_TRUE(iter != urls_requested.end());
1071 if (allowed_domain.empty()) {
1072 EXPECT_TRUE(
1073 !iter->second.HasHeader(safe_search_util::kGoogleAppsAllowedDomains));
1074 return;
1075 }
1076
1077 std::string header;
1078 iter->second.GetHeader(safe_search_util::kGoogleAppsAllowedDomains,
1079 &header);
1080 EXPECT_EQ(header, allowed_domain);
1081 }
1082
1083 static bool FetchSubresource(content::WebContents* web_contents,
1084 const GURL& url) {
1085 std::string script(
1086 "var xhr = new XMLHttpRequest();"
1087 "xhr.open('GET', '");
1088 script += url.spec() +
1089 "', true);"
1090 "xhr.onload = function (e) {"
1091 " if (xhr.readyState === 4) {"
1092 " window.domAutomationController.send(xhr.status === 200);"
1093 " }"
1094 "};"
1095 "xhr.onerror = function () {"
1096 " window.domAutomationController.send(false);"
1097 "};"
1098 "xhr.send(null)";
1099 bool xhr_result = false;
1100 bool execute_result =
1101 content::ExecuteScriptAndExtractBool(web_contents, script, &xhr_result);
1102 return xhr_result && execute_result;
treib2b188052015-04-17 12:32:501103 }
1104
Carlos IL0ea4e592018-05-11 01:51:571105 bool IsShowingInterstitial(content::WebContents* tab) {
Carlos IL5a9e7512019-06-13 22:35:281106 security_interstitials::SecurityInterstitialTabHelper* helper =
1107 security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
1108 tab);
1109 if (!helper) {
1110 return false;
Carlos IL0ea4e592018-05-11 01:51:571111 }
Carlos IL5a9e7512019-06-13 22:35:281112 return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() !=
1113 nullptr;
Carlos IL0ea4e592018-05-11 01:51:571114 }
1115
1116 void WaitForInterstitial(content::WebContents* tab) {
Carlos IL5a9e7512019-06-13 22:35:281117 ASSERT_TRUE(IsShowingInterstitial(tab));
1118 ASSERT_TRUE(WaitForRenderFrameReady(tab->GetMainFrame()));
Carlos IL0ea4e592018-05-11 01:51:571119 }
1120
Luke Zielinski389909fa2018-06-10 02:10:561121 int IsExtendedReportingCheckboxVisibleOnInterstitial() {
1122 const std::string command = base::StringPrintf(
1123 "var node = document.getElementById('extended-reporting-opt-in');"
1124 "if (node) {"
1125 " window.domAutomationController.send(node.offsetWidth > 0 || "
1126 " node.offsetHeight > 0 ? %d : %d);"
1127 "} else {"
1128 // The node should be present but not visible, so trigger an error
1129 // by sending false if it's not present.
1130 " window.domAutomationController.send(%d);"
1131 "}",
1132 security_interstitials::CMD_TEXT_FOUND,
1133 security_interstitials::CMD_TEXT_NOT_FOUND,
1134 security_interstitials::CMD_ERROR);
1135
1136 content::WebContents* tab =
1137 browser()->tab_strip_model()->GetActiveWebContents();
1138 WaitForInterstitial(tab);
1139 int result = 0;
Carlos IL5a9e7512019-06-13 22:35:281140 EXPECT_TRUE(content::ExecuteScriptAndExtractInt(tab->GetMainFrame(),
1141 command, &result));
Luke Zielinski389909fa2018-06-10 02:10:561142 return result;
1143 }
1144
Carlos IL0ea4e592018-05-11 01:51:571145 void SendInterstitialCommand(
1146 content::WebContents* tab,
1147 security_interstitials::SecurityInterstitialCommand command) {
Carlos IL5a9e7512019-06-13 22:35:281148 security_interstitials::SecurityInterstitialTabHelper* helper =
1149 security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
1150 tab);
1151 helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
1152 ->CommandReceived(base::NumberToString(command));
1153 return;
Carlos IL0ea4e592018-05-11 01:51:571154 }
1155
Carlos IL5a9e7512019-06-13 22:35:281156 MockConfigurationPolicyProvider provider_;
1157 std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
1158 extensions::ScopedIgnoreContentVerifierForTest ignore_content_verifier_;
1159 extensions::ExtensionUpdater::ScopedSkipScheduledCheckForTest
1160 skip_scheduled_extension_checks_;
Carlos IL0ea4e592018-05-11 01:51:571161};
1162
[email protected]f900367b22012-09-11 16:08:361163#if defined(OS_WIN)
1164// This policy only exists on Windows.
1165
1166// Sets the locale policy before the browser is started.
1167class LocalePolicyTest : public PolicyTest {
1168 public:
1169 LocalePolicyTest() {}
nickddb02ac2015-04-24 20:45:381170 ~LocalePolicyTest() override {}
[email protected]f900367b22012-09-11 16:08:361171
nickddb02ac2015-04-24 20:45:381172 void SetUpInProcessBrowserTestFixture() override {
[email protected]f900367b22012-09-11 16:08:361173 PolicyTest::SetUpInProcessBrowserTestFixture();
1174 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091175 policies.Set(key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY,
1176 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301177 std::make_unique<base::Value>("fr"), nullptr);
[email protected]f900367b22012-09-11 16:08:361178 provider_.UpdateChromePolicy(policies);
1179 // The "en-US" ResourceBundle is always loaded before this step for tests,
1180 // but in this test we want the browser to load the bundle as it
1181 // normally would.
Lei Zhang7640d542017-10-03 16:26:491182 ui::ResourceBundle::CleanupSharedInstance();
[email protected]f900367b22012-09-11 16:08:361183 }
1184};
1185
1186IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
1187 // Verifies that the default locale can be overridden with policy.
1188 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
[email protected]19506d542013-10-15 23:11:061189 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
[email protected]a04db822013-12-11 19:14:401190 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
1191 base::string16 title;
[email protected]f900367b22012-09-11 16:08:361192 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
1193 EXPECT_EQ(french_title, title);
1194
1195 // Make sure this is really French and differs from the English title.
Francois Doraye6fb2d02017-10-18 21:29:131196 base::ScopedAllowBlockingForTesting allow_blocking;
[email protected]f900367b22012-09-11 16:08:361197 std::string loaded =
1198 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
1199 EXPECT_EQ("en-US", loaded);
[email protected]a04db822013-12-11 19:14:401200 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
[email protected]f900367b22012-09-11 16:08:361201 EXPECT_NE(french_title, english_title);
1202}
1203#endif
1204
Alexander Hendrich55d0b0d92018-05-08 11:29:101205#if defined(OS_CHROMEOS)
Zakhar Voit1f16c5e2018-10-26 12:08:231206IN_PROC_BROWSER_TEST_F(LoginPolicyTestBase, PRE_AllowedLanguages) {
Alexander Hendrich55d0b0d92018-05-08 11:29:101207 SkipToLoginScreen();
1208 LogIn(kAccountId, kAccountPassword, kEmptyServices);
1209
Jit Yao Yapd219c5f2019-05-24 13:07:431210 Profile* const profile = GetProfileForActiveUser();
Alexander Hendrich9ce49262018-05-29 13:35:461211 PrefService* prefs = profile->GetPrefs();
1212
1213 // Set locale and preferred languages to "en-US".
Ran Ji73f3b432018-07-15 22:10:271214 prefs->SetString(language::prefs::kApplicationLocale, "en-US");
Alexandre Frechette572755b2019-02-13 22:30:201215 prefs->SetString(language::prefs::kPreferredLanguages, "en-US");
Alexander Hendrich9ce49262018-05-29 13:35:461216
1217 // Set policy to only allow "fr" as locale.
1218 std::unique_ptr<base::DictionaryValue> policy =
1219 std::make_unique<base::DictionaryValue>();
Zakhar Voit1f16c5e2018-10-26 12:08:231220 base::ListValue allowed_languages;
1221 allowed_languages.AppendString("fr");
1222 policy->SetKey(key::kAllowedLanguages, std::move(allowed_languages));
Roman Sorokin886bf37b2019-04-28 05:57:271223 user_policy_helper()->SetPolicyAndWait(*policy, base::DictionaryValue(),
1224 profile);
Alexander Hendrich9ce49262018-05-29 13:35:461225}
1226
Zakhar Voit1f16c5e2018-10-26 12:08:231227IN_PROC_BROWSER_TEST_F(LoginPolicyTestBase, AllowedLanguages) {
Alexander Hendrich9ce49262018-05-29 13:35:461228 LogIn(kAccountId, kAccountPassword, kEmptyServices);
1229
Jit Yao Yapd219c5f2019-05-24 13:07:431230 Profile* const profile = GetProfileForActiveUser();
Alexander Hendrich9ce49262018-05-29 13:35:461231 const PrefService* prefs = profile->GetPrefs();
Alexander Hendrich55d0b0d92018-05-08 11:29:101232
1233 // Verifies that the default locale has been overridden by policy
1234 // (see |GetMandatoryPoliciesValue|)
1235 Browser* browser = CreateBrowser(profile);
Ran Ji73f3b432018-07-15 22:10:271236 EXPECT_EQ("fr", prefs->GetString(language::prefs::kApplicationLocale));
Alexander Hendrich55d0b0d92018-05-08 11:29:101237 ui_test_utils::NavigateToURL(browser, GURL(chrome::kChromeUINewTabURL));
1238 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
1239 base::string16 title;
1240 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser, &title));
1241 EXPECT_EQ(french_title, title);
1242
1243 // Make sure this is really French and differs from the English title.
1244 base::ScopedAllowBlockingForTesting allow_blocking;
1245 std::string loaded =
1246 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
1247 EXPECT_EQ("en-US", loaded);
1248 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
1249 EXPECT_NE(french_title, english_title);
Alexander Hendrich9ce49262018-05-29 13:35:461250
1251 // Verifiy that the enforced locale is added into the list of
1252 // preferred languages.
Alexandre Frechette572755b2019-02-13 22:30:201253 EXPECT_EQ("fr", prefs->GetString(language::prefs::kPreferredLanguages));
Alexander Hendrich55d0b0d92018-05-08 11:29:101254}
Alexander Hendricha4c39532018-06-27 08:33:051255
1256IN_PROC_BROWSER_TEST_F(LoginPolicyTestBase, AllowedInputMethods) {
1257 SkipToLoginScreen();
1258 LogIn(kAccountId, kAccountPassword, kEmptyServices);
1259
Jit Yao Yapd219c5f2019-05-24 13:07:431260 Profile* const profile = GetProfileForActiveUser();
Alexander Hendricha4c39532018-06-27 08:33:051261
1262 chromeos::input_method::InputMethodManager* imm =
1263 chromeos::input_method::InputMethodManager::Get();
1264 ASSERT_TRUE(imm);
1265 scoped_refptr<chromeos::input_method::InputMethodManager::State> ime_state =
1266 imm->GetActiveIMEState();
1267 ASSERT_TRUE(ime_state.get());
1268
1269 std::vector<std::string> input_methods;
1270 input_methods.emplace_back("xkb:us::eng");
1271 input_methods.emplace_back("xkb:fr::fra");
1272 input_methods.emplace_back("xkb:de::ger");
1273 EXPECT_TRUE(imm->MigrateInputMethods(&input_methods));
1274
1275 // No restrictions and current input method should be "xkb:us::eng" (default).
1276 EXPECT_EQ(0U, ime_state->GetAllowedInputMethods().size());
1277 EXPECT_EQ(input_methods[0], ime_state->GetCurrentInputMethod().id());
1278 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[1]));
1279 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[2]));
1280
1281 // Set policy to only allow "xkb:fr::fra", "xkb:de::ger" an an invalid value
1282 // as input method.
1283 std::unique_ptr<base::DictionaryValue> policy =
1284 std::make_unique<base::DictionaryValue>();
1285 base::ListValue allowed_input_methods;
1286 allowed_input_methods.AppendString("xkb:fr::fra");
1287 allowed_input_methods.AppendString("xkb:de::ger");
1288 allowed_input_methods.AppendString("invalid_value_will_be_ignored");
1289 policy->SetKey(key::kAllowedInputMethods, std::move(allowed_input_methods));
Roman Sorokin886bf37b2019-04-28 05:57:271290 user_policy_helper()->SetPolicyAndWait(*policy, base::DictionaryValue(),
1291 profile);
Alexander Hendricha4c39532018-06-27 08:33:051292
1293 // Only "xkb:fr::fra", "xkb:de::ger" should be allowed, current input method
1294 // should be "xkb:fr::fra", enabling "xkb:us::eng" should not be possible,
1295 // enabling "xkb:de::ger" should be possible.
1296 EXPECT_EQ(2U, ime_state->GetAllowedInputMethods().size());
1297 EXPECT_EQ(2U, ime_state->GetActiveInputMethods()->size());
1298 EXPECT_EQ(input_methods[1], ime_state->GetCurrentInputMethod().id());
1299 EXPECT_FALSE(ime_state->EnableInputMethod(input_methods[0]));
1300 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[2]));
1301
1302 // Set policy to only allow an invalid value as input method.
1303 std::unique_ptr<base::DictionaryValue> policy_invalid =
1304 std::make_unique<base::DictionaryValue>();
1305 base::ListValue invalid_input_methods;
1306 invalid_input_methods.AppendString("invalid_value_will_be_ignored");
1307 policy_invalid->SetKey(key::kAllowedInputMethods,
1308 std::move(invalid_input_methods));
Roman Sorokin886bf37b2019-04-28 05:57:271309 user_policy_helper()->SetPolicyAndWait(*policy_invalid,
1310 base::DictionaryValue(), profile);
Alexander Hendricha4c39532018-06-27 08:33:051311
1312 // No restrictions and current input method should still be "xkb:fr::fra".
1313 EXPECT_EQ(0U, ime_state->GetAllowedInputMethods().size());
1314 EXPECT_EQ(input_methods[1], ime_state->GetCurrentInputMethod().id());
1315 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[0]));
1316 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[2]));
1317
1318 // Allow all input methods again.
Roman Sorokin886bf37b2019-04-28 05:57:271319 user_policy_helper()->SetPolicyAndWait(base::DictionaryValue(),
1320 base::DictionaryValue(), profile);
Alexander Hendricha4c39532018-06-27 08:33:051321
1322 // No restrictions and current input method should still be "xkb:fr::fra".
1323 EXPECT_EQ(0U, ime_state->GetAllowedInputMethods().size());
1324 EXPECT_EQ(input_methods[1], ime_state->GetCurrentInputMethod().id());
1325 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[0]));
1326 EXPECT_TRUE(ime_state->EnableInputMethod(input_methods[2]));
1327}
1328
Jit Yao Yapd219c5f2019-05-24 13:07:431329class StartupBrowserWindowLaunchSuppressedTest : public LoginPolicyTestBase {
1330 public:
1331 StartupBrowserWindowLaunchSuppressedTest() = default;
1332
1333 void SetUpPolicy(bool enabled) {
1334 std::unique_ptr<base::DictionaryValue> policy =
1335 std::make_unique<base::DictionaryValue>();
1336
1337 policy->SetKey(key::kStartupBrowserWindowLaunchSuppressed,
1338 base::Value(enabled));
1339
1340 user_policy_helper()->SetPolicy(*policy, base::DictionaryValue());
1341 }
1342
1343 void CheckLaunchedBrowserCount(unsigned int count) {
1344 SkipToLoginScreen();
1345 LogIn(kAccountId, kAccountPassword, kEmptyServices);
1346
1347 Profile* const profile = GetProfileForActiveUser();
1348
1349 ASSERT_EQ(count, chrome::GetBrowserCount(profile));
1350 }
1351
1352 private:
1353 DISALLOW_COPY_AND_ASSIGN(StartupBrowserWindowLaunchSuppressedTest);
1354};
1355
1356// Test that the browser window is not launched when
1357// StartupBrowserWindowLaunchSuppressed is set to true.
1358IN_PROC_BROWSER_TEST_F(StartupBrowserWindowLaunchSuppressedTest,
1359 TrueDoesNotAllowBrowserWindowLaunch) {
1360 SetUpPolicy(true);
1361 CheckLaunchedBrowserCount(0u);
1362}
1363
1364// Test that the browser window is launched when
1365// StartupBrowserWindowLaunchSuppressed is set to false.
1366IN_PROC_BROWSER_TEST_F(StartupBrowserWindowLaunchSuppressedTest,
1367 FalseAllowsBrowserWindowLaunch) {
1368 SetUpPolicy(false);
1369 CheckLaunchedBrowserCount(1u);
1370}
1371
Alexander Hendricha4c39532018-06-27 08:33:051372#endif // defined(OS_CHROMEOS)
Alexander Hendrich55d0b0d92018-05-08 11:29:101373
[email protected]3757c7d2012-07-23 11:24:361374IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
[email protected]b8b27052012-08-29 14:05:161375 // Verifies that the bookmarks bar can be forced to always or never show up.
1376
[email protected]3757c7d2012-07-23 11:24:361377 // Test starts in about:blank.
1378 PrefService* prefs = browser()->profile()->GetPrefs();
tfarina3bddbe112014-08-28 05:29:321379 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
1380 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
[email protected]3757c7d2012-07-23 11:24:361381 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
1382
1383 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091384 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
1385 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301386 std::make_unique<base::Value>(true), nullptr);
[email protected]161245d2013-01-09 14:28:111387 UpdateProviderPolicy(policies);
tfarina3bddbe112014-08-28 05:29:321388 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
1389 EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
[email protected]3757c7d2012-07-23 11:24:361390 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
[email protected]3757c7d2012-07-23 11:24:361391}
1392
[email protected]96da69d12013-05-28 17:00:051393IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
[email protected]b8b27052012-08-29 14:05:161394 // Verifies that cookies are deleted on shutdown. This test is split in 3
1395 // parts because it spans 2 browser restarts.
1396
[email protected]b561aab2012-08-27 20:17:491397 Profile* profile = browser()->profile();
1398 GURL url(kURL);
1399 // No cookies at startup.
1400 EXPECT_TRUE(content::GetCookies(profile, url).empty());
1401 // Set a cookie now.
Clark DuVall385b5a52018-06-14 21:33:321402 std::string value = base::StrCat({kCookieValue, kCookieOptions});
[email protected]b561aab2012-08-27 20:17:491403 EXPECT_TRUE(content::SetCookie(profile, url, value));
1404 // Verify it was set.
1405 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
1406}
1407
[email protected]96da69d12013-05-28 17:00:051408IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
[email protected]b561aab2012-08-27 20:17:491409 // Verify that the cookie persists across restarts.
1410 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
1411 // Now set the policy and the cookie should be gone after another restart.
1412 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091413 policies.Set(key::kDefaultCookiesSetting, POLICY_LEVEL_MANDATORY,
1414 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Clark DuVall385b5a52018-06-14 21:33:321415 std::make_unique<base::Value>(CONTENT_SETTING_SESSION_ONLY),
1416 nullptr);
[email protected]161245d2013-01-09 14:28:111417 UpdateProviderPolicy(policies);
[email protected]b561aab2012-08-27 20:17:491418}
1419
[email protected]96da69d12013-05-28 17:00:051420IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
[email protected]b561aab2012-08-27 20:17:491421 // Verify that the cookie is gone.
1422 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
1423}
1424
Clark DuVall385b5a52018-06-14 21:33:321425IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_WebsiteCookiesSetting) {
1426 // Verifies that cookies are deleted on shutdown. This test is split in 3
1427 // parts because it spans 2 browser restarts.
1428
1429 Profile* profile = browser()->profile();
1430 GURL url(kURL);
1431 // No cookies at startup.
1432 EXPECT_TRUE(content::GetCookies(profile, url).empty());
1433 // Set a cookie now.
1434 std::string value = base::StrCat({kCookieValue, kCookieOptions});
1435 EXPECT_TRUE(content::SetCookie(profile, url, value));
1436 // Verify it was set.
1437 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
1438}
1439
1440IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_WebsiteCookiesSetting) {
1441 // Verify that the cookie persists across restarts.
1442 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
1443 // Now set the policy and the cookie should be gone after another restart.
1444 HostContentSettingsMapFactory::GetForProfile(browser()->profile())
1445 ->SetWebsiteSettingDefaultScope(
1446 GURL(kURL), GURL(kURL), CONTENT_SETTINGS_TYPE_COOKIES, std::string(),
1447 std::make_unique<base::Value>(CONTENT_SETTING_SESSION_ONLY));
1448}
1449
1450IN_PROC_BROWSER_TEST_F(PolicyTest, WebsiteCookiesSetting) {
1451 // Verify that the cookie is gone.
1452 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
1453}
1454
[email protected]771c4b92012-08-29 10:19:271455IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
[email protected]f53b4802012-12-20 17:04:231456 MakeRequestFail make_request_fail("search.example");
[email protected]d1208ba32012-11-08 11:10:331457
[email protected]771c4b92012-08-29 10:19:271458 // Verifies that a default search is made using the provider configured via
1459 // policy. Also checks that default search can be completely disabled.
[email protected]6778fed2013-12-24 20:09:371460 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
[email protected]771c4b92012-08-29 10:19:271461 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
[email protected]250bf232012-10-15 14:36:331462 const std::string kAlternateURL0(
1463 "http://search.example/search#q={searchTerms}");
1464 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
[email protected]39682d12013-07-31 23:02:051465 const std::string kImageURL("http://test.com/searchbyimage/upload");
1466 const std::string kImageURLPostParams(
1467 "image_content=content,image_url=http://test.com/test.png");
[email protected]041238dd2013-08-19 21:05:121468 const std::string kNewTabURL("http://search.example/newtab");
[email protected]771c4b92012-08-29 10:19:271469
1470 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1471 browser()->profile());
thestigf80564462015-09-29 23:12:081472 search_test_utils::WaitForTemplateURLServiceToLoad(service);
jeffschiller8aa7a4e2017-04-23 02:22:101473 const TemplateURL* default_search = service->GetDefaultSearchProvider();
[email protected]771c4b92012-08-29 10:19:271474 ASSERT_TRUE(default_search);
1475 EXPECT_NE(kKeyword, default_search->keyword());
1476 EXPECT_NE(kSearchURL, default_search->url());
[email protected]250bf232012-10-15 14:36:331477 EXPECT_FALSE(
1478 default_search->alternate_urls().size() == 2 &&
1479 default_search->alternate_urls()[0] == kAlternateURL0 &&
[email protected]008987b02013-01-03 21:22:431480 default_search->alternate_urls()[1] == kAlternateURL1 &&
[email protected]39682d12013-07-31 23:02:051481 default_search->image_url() == kImageURL &&
[email protected]041238dd2013-08-19 21:05:121482 default_search->image_url_post_params() == kImageURLPostParams &&
1483 default_search->new_tab_url() == kNewTabURL);
[email protected]771c4b92012-08-29 10:19:271484
1485 // Override the default search provider using policies.
1486 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091487 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
1488 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301489 std::make_unique<base::Value>(true), nullptr);
dcheng3b344bc22016-05-10 02:26:091490 policies.Set(key::kDefaultSearchProviderKeyword, POLICY_LEVEL_MANDATORY,
1491 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301492 std::make_unique<base::Value>(kKeyword), nullptr);
dcheng3b344bc22016-05-10 02:26:091493 policies.Set(key::kDefaultSearchProviderSearchURL, POLICY_LEVEL_MANDATORY,
1494 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301495 std::make_unique<base::Value>(kSearchURL), nullptr);
dcheng3b344bc22016-05-10 02:26:091496 std::unique_ptr<base::ListValue> alternate_urls(new base::ListValue);
[email protected]250bf232012-10-15 14:36:331497 alternate_urls->AppendString(kAlternateURL0);
1498 alternate_urls->AppendString(kAlternateURL1);
1499 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:091500 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
1501 std::move(alternate_urls), nullptr);
dcheng3b344bc22016-05-10 02:26:091502 policies.Set(key::kDefaultSearchProviderImageURL, POLICY_LEVEL_MANDATORY,
1503 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301504 std::make_unique<base::Value>(kImageURL), nullptr);
[email protected]39682d12013-07-31 23:02:051505 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
dcheng3b344bc22016-05-10 02:26:091506 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301507 std::make_unique<base::Value>(kImageURLPostParams), nullptr);
dcheng3b344bc22016-05-10 02:26:091508 policies.Set(key::kDefaultSearchProviderNewTabURL, POLICY_LEVEL_MANDATORY,
1509 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301510 std::make_unique<base::Value>(kNewTabURL), nullptr);
[email protected]161245d2013-01-09 14:28:111511 UpdateProviderPolicy(policies);
[email protected]771c4b92012-08-29 10:19:271512 default_search = service->GetDefaultSearchProvider();
1513 ASSERT_TRUE(default_search);
1514 EXPECT_EQ(kKeyword, default_search->keyword());
1515 EXPECT_EQ(kSearchURL, default_search->url());
[email protected]250bf232012-10-15 14:36:331516 EXPECT_EQ(2U, default_search->alternate_urls().size());
1517 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1518 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
[email protected]39682d12013-07-31 23:02:051519 EXPECT_EQ(kImageURL, default_search->image_url());
1520 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
[email protected]041238dd2013-08-19 21:05:121521 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
[email protected]771c4b92012-08-29 10:19:271522
1523 // Verify that searching from the omnibox uses kSearchURL.
1524 chrome::FocusLocationBar(browser());
Evan Stadead9765ab2019-07-02 17:02:411525 ui_test_utils::SendToOmniboxAndSubmit(browser(), "stuff to search for");
1526 OmniboxEditModel* model =
1527 browser()->window()->GetLocationBar()->GetOmniboxView()->model();
[email protected]31511bbc2013-06-18 17:40:571528 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
[email protected]617ee962013-01-29 20:49:121529 content::WebContents* web_contents =
1530 browser()->tab_strip_model()->GetActiveWebContents();
[email protected]771c4b92012-08-29 10:19:271531 GURL expected("http://search.example/search?q=stuff+to+search+for");
1532 EXPECT_EQ(expected, web_contents->GetURL());
1533
1534 // Verify that searching from the omnibox can be disabled.
[email protected]8e09c7af2014-06-10 11:46:171535 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
dcheng3b344bc22016-05-10 02:26:091536 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
1537 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301538 std::make_unique<base::Value>(false), nullptr);
[email protected]771c4b92012-08-29 10:19:271539 EXPECT_TRUE(service->GetDefaultSearchProvider());
[email protected]161245d2013-01-09 14:28:111540 UpdateProviderPolicy(policies);
[email protected]771c4b92012-08-29 10:19:271541 EXPECT_FALSE(service->GetDefaultSearchProvider());
Evan Stadead9765ab2019-07-02 17:02:411542 ui_test_utils::SendToOmniboxAndSubmit(browser(), "should not work");
[email protected]771c4b92012-08-29 10:19:271543 // This means that submitting won't trigger any action.
[email protected]31511bbc2013-06-18 17:40:571544 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
[email protected]8e09c7af2014-06-10 11:46:171545 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
[email protected]771c4b92012-08-29 10:19:271546}
1547
emaxxb88b2c62017-01-31 17:50:191548IN_PROC_BROWSER_TEST_F(PolicyTest, SeparateProxyPoliciesMerging) {
[email protected]f97bd482013-11-21 13:04:281549 // Add an individual proxy policy value.
1550 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091551 policies.Set(key::kProxyServerMode, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Jinho Bang2a491912018-01-16 07:21:301552 POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(3), nullptr);
[email protected]f97bd482013-11-21 13:04:281553 UpdateProviderPolicy(policies);
1554
1555 // It should be removed and replaced with a dictionary.
1556 PolicyMap expected;
dcheng08cfe9ba2016-04-14 17:46:451557 std::unique_ptr<base::DictionaryValue> expected_value(
1558 new base::DictionaryValue);
[email protected]f97bd482013-11-21 13:04:281559 expected_value->SetInteger(key::kProxyServerMode, 3);
dcheng3b344bc22016-05-10 02:26:091560 expected.Set(key::kProxySettings, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1561 POLICY_SOURCE_CLOUD, std::move(expected_value), nullptr);
Bartosz Fabianowski0248c492018-07-02 13:44:321562#if defined(OS_CHROMEOS)
1563 SetEnterpriseUsersDefaults(&expected);
1564#endif
[email protected]f97bd482013-11-21 13:04:281565
1566 // Check both the browser and the profile.
1567 const PolicyMap& actual_from_browser =
1568 g_browser_process->browser_policy_connector()
1569 ->GetPolicyService()
1570 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1571 EXPECT_TRUE(expected.Equals(actual_from_browser));
1572 const PolicyMap& actual_from_profile =
Xi Hanfe39afc62019-04-29 14:50:141573 browser()
1574 ->profile()
1575 ->GetProfilePolicyConnector()
[email protected]f97bd482013-11-21 13:04:281576 ->policy_service()
1577 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1578 EXPECT_TRUE(expected.Equals(actual_from_profile));
1579}
1580
ljusten98684cb72016-10-11 13:26:181581IN_PROC_BROWSER_TEST_F(PolicyTest, LegacySafeSearch) {
1582 static_assert(safe_search_util::YOUTUBE_RESTRICT_OFF == 0 &&
1583 safe_search_util::YOUTUBE_RESTRICT_MODERATE == 1 &&
1584 safe_search_util::YOUTUBE_RESTRICT_STRICT == 2 &&
1585 safe_search_util::YOUTUBE_RESTRICT_COUNT == 3,
1586 "This test relies on mapping ints to enum values.");
1587
1588 // Go over all combinations of (undefined, true, false) for the policies
1589 // ForceSafeSearch, ForceGoogleSafeSearch and ForceYouTubeSafetyMode as well
1590 // as (undefined, off, moderate, strict) for ForceYouTubeRestrict and make
1591 // sure the prefs are set as expected.
1592 const int num_restrict_modes = 1 + safe_search_util::YOUTUBE_RESTRICT_COUNT;
1593 for (int i = 0; i < 3 * 3 * 3 * num_restrict_modes; i++) {
1594 int val = i;
1595 int legacy_safe_search = val % 3; val /= 3;
1596 int google_safe_search = val % 3; val /= 3;
1597 int legacy_youtube = val % 3; val /= 3;
1598 int youtube_restrict = val % num_restrict_modes;
1599
1600 // Override the default SafeSearch setting using policies.
1601 ApplySafeSearchPolicy(
1602 legacy_safe_search == 0
1603 ? nullptr
Jinho Bang2a491912018-01-16 07:21:301604 : std::make_unique<base::Value>(legacy_safe_search == 1),
ljusten98684cb72016-10-11 13:26:181605 google_safe_search == 0
1606 ? nullptr
Jinho Bang2a491912018-01-16 07:21:301607 : std::make_unique<base::Value>(google_safe_search == 1),
ljusten98684cb72016-10-11 13:26:181608 legacy_youtube == 0
1609 ? nullptr
Jinho Bang2a491912018-01-16 07:21:301610 : std::make_unique<base::Value>(legacy_youtube == 1),
ljusten98684cb72016-10-11 13:26:181611 youtube_restrict == 0
1612 ? nullptr // subtracting 1 gives 0,1,2, see above
Jinho Bang2a491912018-01-16 07:21:301613 : std::make_unique<base::Value>(youtube_restrict - 1));
ljusten98684cb72016-10-11 13:26:181614
1615 // The legacy ForceSafeSearch policy should only have an effect if none of
1616 // the other 3 policies are defined.
1617 bool legacy_safe_search_in_effect =
1618 google_safe_search == 0 && legacy_youtube == 0 &&
1619 youtube_restrict == 0 && legacy_safe_search != 0;
1620 bool legacy_safe_search_enabled =
1621 legacy_safe_search_in_effect && legacy_safe_search == 1;
1622
1623 // Likewise, ForceYouTubeSafetyMode should only have an effect if
1624 // ForceYouTubeRestrict is not set.
1625 bool legacy_youtube_in_effect =
1626 youtube_restrict == 0 && legacy_youtube != 0;
1627 bool legacy_youtube_enabled =
1628 legacy_youtube_in_effect && legacy_youtube == 1;
1629
1630 // Consistency check, can't have both legacy modes at the same time.
1631 EXPECT_FALSE(legacy_youtube_in_effect && legacy_safe_search_in_effect);
1632
1633 // Google safe search can be triggered by the ForceGoogleSafeSearch policy
1634 // or the legacy safe search mode.
1635 PrefService* prefs = browser()->profile()->GetPrefs();
1636 EXPECT_EQ(google_safe_search != 0 || legacy_safe_search_in_effect,
1637 prefs->IsManagedPreference(prefs::kForceGoogleSafeSearch));
1638 EXPECT_EQ(google_safe_search == 1 || legacy_safe_search_enabled,
1639 prefs->GetBoolean(prefs::kForceGoogleSafeSearch));
1640
1641 // YouTube restrict mode can be triggered by the ForceYouTubeRestrict policy
1642 // or any of the legacy modes.
1643 EXPECT_EQ(youtube_restrict != 0 || legacy_safe_search_in_effect ||
1644 legacy_youtube_in_effect,
1645 prefs->IsManagedPreference(prefs::kForceYouTubeRestrict));
1646
1647 if (youtube_restrict != 0) {
1648 // The ForceYouTubeRestrict policy should map directly to the pref.
1649 EXPECT_EQ(youtube_restrict - 1,
1650 prefs->GetInteger(prefs::kForceYouTubeRestrict));
1651 } else {
1652 // The legacy modes should result in MODERATE strictness, if enabled.
1653 safe_search_util::YouTubeRestrictMode expected_mode =
1654 legacy_safe_search_enabled || legacy_youtube_enabled
1655 ? safe_search_util::YOUTUBE_RESTRICT_MODERATE
1656 : safe_search_util::YOUTUBE_RESTRICT_OFF;
1657 EXPECT_EQ(prefs->GetInteger(prefs::kForceYouTubeRestrict), expected_mode);
1658 }
1659 }
1660}
1661
1662IN_PROC_BROWSER_TEST_F(PolicyTest, ForceGoogleSafeSearch) {
John Abd-El-Malek9fb60492018-08-02 04:28:501663 base::Lock lock;
1664 std::set<GURL> google_urls_requested;
1665 content::URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
1666 [&](content::URLLoaderInterceptor::RequestParams* params) -> bool {
1667 if (params->url_request.url.host() != "google.com")
1668 return false;
1669 base::AutoLock auto_lock(lock);
1670 google_urls_requested.insert(params->url_request.url);
1671 std::string relative_path("chrome/test/data/simple.html");
1672 content::URLLoaderInterceptor::WriteResponse(relative_path,
1673 params->client.get());
1674 return true;
1675 }));
[email protected]d1208ba32012-11-08 11:10:331676
1677 // Verifies that requests to Google Search engine with the SafeSearch
1678 // enabled set the safe=active&ssui=on parameters at the end of the query.
[email protected]d1208ba32012-11-08 11:10:331679 // First check that nothing happens.
John Abd-El-Malek9fb60492018-08-02 04:28:501680 CheckSafeSearch(browser(), false);
[email protected]d1208ba32012-11-08 11:10:331681
ljusten98684cb72016-10-11 13:26:181682 // Go over all combinations of (undefined, true, false) for the
1683 // ForceGoogleSafeSearch policy.
1684 for (int safe_search = 0; safe_search < 3; safe_search++) {
1685 // Override the Google safe search policy.
jdoerrie239723572017-03-02 12:09:191686 ApplySafeSearchPolicy(nullptr, // ForceSafeSearch
1687 safe_search == 0 // ForceGoogleSafeSearch
1688 ? nullptr
Jinho Bang2a491912018-01-16 07:21:301689 : std::make_unique<base::Value>(safe_search == 1),
Lukasz Anforowicz0e9fdcd2017-09-28 13:00:031690 nullptr, // ForceYouTubeSafetyMode
1691 nullptr); // ForceYouTubeRestrict
ljusten98684cb72016-10-11 13:26:181692 // Verify that the safe search pref behaves the way we expect.
treib2b188052015-04-17 12:32:501693 PrefService* prefs = browser()->profile()->GetPrefs();
ljusten98684cb72016-10-11 13:26:181694 EXPECT_EQ(safe_search != 0,
treib2b188052015-04-17 12:32:501695 prefs->IsManagedPreference(prefs::kForceGoogleSafeSearch));
ljusten98684cb72016-10-11 13:26:181696 EXPECT_EQ(safe_search == 1,
treib2b188052015-04-17 12:32:501697 prefs->GetBoolean(prefs::kForceGoogleSafeSearch));
[email protected]d1208ba32012-11-08 11:10:331698
ljusten98684cb72016-10-11 13:26:181699 // Verify that safe search actually works.
John Abd-El-Malek9fb60492018-08-02 04:28:501700 CheckSafeSearch(browser(), safe_search == 1);
1701
1702 GURL google_url(GetExpectedSearchURL(safe_search == 1));
1703
1704 {
1705 // Verify that the network request is what we expect.
1706 base::AutoLock auto_lock(lock);
1707 ASSERT_TRUE(google_urls_requested.find(google_url) !=
1708 google_urls_requested.end());
1709 google_urls_requested.clear();
1710 }
1711
1712 {
1713 // Now check subresource loads.
1714 FetchSubresource(browser()->tab_strip_model()->GetActiveWebContents(),
1715 GURL("http://google.com/"));
1716
1717 base::AutoLock auto_lock(lock);
1718 ASSERT_TRUE(google_urls_requested.find(google_url) !=
1719 google_urls_requested.end());
1720 }
1721 }
1722}
1723
John Abd-El-Malekd2b62ee2018-11-20 07:43:341724class PolicyTestSafeSearchRedirect : public PolicyTest {
1725 public:
1726 PolicyTestSafeSearchRedirect() = default;
1727
1728 private:
1729 void SetUpOnMainThread() override {
1730 // The test makes requests to google.com which we want to redirect to the
1731 // test server.
1732 host_resolver()->AddRule("*", "127.0.0.1");
1733
1734 // The production code only allows known ports (80 for http and 443 for
1735 // https), but the test server runs on a random port.
1736 google_util::IgnorePortNumbersForGoogleURLChecksForTesting();
1737 }
1738
1739 void SetUpCommandLine(base::CommandLine* command_line) override {
1740 // HTTPS server only serves a valid cert for localhost, so this is needed to
1741 // load pages from "www.google.com" without an interstitial.
1742 command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
1743 }
1744
1745 DISALLOW_COPY_AND_ASSIGN(PolicyTestSafeSearchRedirect);
1746};
1747
1748IN_PROC_BROWSER_TEST_F(PolicyTestSafeSearchRedirect, ForceGoogleSafeSearch) {
1749 net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
Alan Cuttera9a96c52019-03-28 07:15:391750 https_server.AddDefaultHandlers(GetChromeTestDataDir());
John Abd-El-Malekd2b62ee2018-11-20 07:43:341751 ASSERT_TRUE(https_server.Start());
1752
1753 ApplySafeSearchPolicy(nullptr, // ForceSafeSearch
1754 std::make_unique<base::Value>(true),
1755 nullptr, // ForceYouTubeSafetyMode
1756 nullptr); // ForceYouTubeRestrict
1757
1758 GURL url = https_server.GetURL("www.google.com",
1759 "/server-redirect?http://google.com/");
1760 CheckSafeSearch(browser(), true, url.spec());
1761}
1762
John Abd-El-Malek9fb60492018-08-02 04:28:501763IN_PROC_BROWSER_TEST_F(PolicyTest, ForceYouTubeRestrict) {
1764 base::Lock lock;
1765 std::map<GURL, net::HttpRequestHeaders> urls_requested;
1766 content::URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
1767 [&](content::URLLoaderInterceptor::RequestParams* params) -> bool {
1768 if (params->url_request.url.host() != "youtube.com")
1769 return false;
1770
1771 base::AutoLock auto_lock(lock);
1772 urls_requested[params->url_request.url] = params->url_request.headers;
1773
1774 std::string relative_path("chrome/test/data/simple.html");
1775 content::URLLoaderInterceptor::WriteResponse(relative_path,
1776 params->client.get());
1777 return true;
1778 }));
1779
1780 for (int youtube_restrict_mode = safe_search_util::YOUTUBE_RESTRICT_OFF;
1781 youtube_restrict_mode < safe_search_util::YOUTUBE_RESTRICT_COUNT;
1782 ++youtube_restrict_mode) {
1783 ApplySafeSearchPolicy(nullptr, // ForceSafeSearch
1784 nullptr, // ForceGoogleSafeSearch
1785 nullptr, // ForceYouTubeSafetyMode
1786 std::make_unique<base::Value>(youtube_restrict_mode));
1787 {
1788 // First check frame requests.
1789 GURL youtube_url("http://youtube.com");
1790 ui_test_utils::NavigateToURL(browser(), youtube_url);
1791
1792 base::AutoLock auto_lock(lock);
1793 CheckYouTubeRestricted(youtube_restrict_mode, urls_requested,
1794 youtube_url);
1795 }
1796
1797 {
1798 // Now check subresource loads.
1799 GURL youtube_script("http://youtube.com/foo.js");
1800 FetchSubresource(browser()->tab_strip_model()->GetActiveWebContents(),
1801 youtube_script);
1802
1803 base::AutoLock auto_lock(lock);
1804 CheckYouTubeRestricted(youtube_restrict_mode, urls_requested,
1805 youtube_script);
1806 }
1807 }
1808}
1809
1810IN_PROC_BROWSER_TEST_F(PolicyTest, AllowedDomainsForApps) {
1811 ASSERT_TRUE(embedded_test_server()->Start());
1812 base::Lock lock;
1813 std::map<GURL, net::HttpRequestHeaders> urls_requested;
1814 content::URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
1815 [&](content::URLLoaderInterceptor::RequestParams* params) -> bool {
1816 base::AutoLock auto_lock(lock);
1817 urls_requested[params->url_request.url] = params->url_request.headers;
1818 return false;
1819 }));
1820
1821 for (int allowed_domains = 0; allowed_domains < 2; ++allowed_domains) {
1822 std::string allowed_domain;
1823 if (allowed_domains) {
1824 PolicyMap policies;
1825 allowed_domain = "foo.com";
1826 SetPolicy(&policies, key::kAllowedDomainsForApps,
1827 std::make_unique<base::Value>(allowed_domain));
1828 UpdateProviderPolicy(policies);
1829 }
1830
1831 {
1832 // First check frame requests.
1833 GURL google_url =
1834 embedded_test_server()->GetURL("google.com", "/empty.html");
1835 ui_test_utils::NavigateToURL(browser(), google_url);
1836
1837 base::AutoLock auto_lock(lock);
1838 CheckAllowedDomainsHeader(allowed_domain, urls_requested, google_url);
1839 }
1840
1841 {
1842 // Now check subresource loads.
1843 GURL google_script =
1844 embedded_test_server()->GetURL("google.com", "/result_queue.js");
1845
1846 FetchSubresource(browser()->tab_strip_model()->GetActiveWebContents(),
1847 google_script);
1848
1849 base::AutoLock auto_lock(lock);
1850 CheckAllowedDomainsHeader(allowed_domain, urls_requested, google_script);
1851 }
1852
1853 {
1854 // Double check that a frame to a non-Google url doesn't have the header.
1855 GURL non_google_url = embedded_test_server()->GetURL("/empty.html");
1856 ui_test_utils::NavigateToURL(browser(), non_google_url);
1857
1858 base::AutoLock auto_lock(lock);
1859 CheckAllowedDomainsHeader(std::string(), urls_requested, non_google_url);
1860 }
treib2b188052015-04-17 12:32:501861 }
[email protected]d1208ba32012-11-08 11:10:331862}
1863
tzik8826eda2016-11-09 04:30:281864IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
[email protected]f5b7f6e2013-12-10 13:57:321865 // This test assumes Gpu access.
kinuko7e9da252017-03-10 07:18:421866 if (!content::GpuDataManager::GetInstance()->HardwareAccelerationEnabled())
[email protected]f5b7f6e2013-12-10 13:57:321867 return;
1868
[email protected]8e09c7af2014-06-10 11:46:171869 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
[email protected]bb34f262012-09-05 09:09:461870 // WebGL is enabled by default.
[email protected]617ee962013-01-29 20:49:121871 content::WebContents* contents =
1872 browser()->tab_strip_model()->GetActiveWebContents();
[email protected]bb34f262012-09-05 09:09:461873 EXPECT_TRUE(IsWebGLEnabled(contents));
1874 // Disable with a policy.
1875 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091876 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Jinho Bang2a491912018-01-16 07:21:301877 POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(true),
jdoerrie239723572017-03-02 12:09:191878 nullptr);
[email protected]161245d2013-01-09 14:28:111879 UpdateProviderPolicy(policies);
[email protected]bb34f262012-09-05 09:09:461880 // Crash and reload the tab to get a new renderer.
1881 content::CrashTab(contents);
1882 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1883 EXPECT_FALSE(IsWebGLEnabled(contents));
1884 // Enable with a policy.
dcheng3b344bc22016-05-10 02:26:091885 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
Jinho Bang2a491912018-01-16 07:21:301886 POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(false),
jdoerrie239723572017-03-02 12:09:191887 nullptr);
[email protected]161245d2013-01-09 14:28:111888 UpdateProviderPolicy(policies);
[email protected]bb34f262012-09-05 09:09:461889 content::CrashTab(contents);
1890 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1891 EXPECT_TRUE(IsWebGLEnabled(contents));
1892}
[email protected]bb34f262012-09-05 09:09:461893
Pavol Markodebb0ff2018-05-07 18:35:411894IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabledByLegacyPolicy) {
1895 // Verifies that access to the developer tools can be disabled by setting the
1896 // legacy DeveloperToolsDisabled policy.
[email protected]ea826362012-09-05 23:31:371897
1898 // Open devtools.
1899 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
[email protected]617ee962013-01-29 20:49:121900 content::WebContents* contents =
1901 browser()->tab_strip_model()->GetActiveWebContents();
binjin828b14162014-12-01 13:04:291902 DevToolsWindow* devtools_window =
[email protected]db90e8a2014-07-07 17:57:351903 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
[email protected]a1406cb2013-10-16 14:30:431904 EXPECT_TRUE(devtools_window);
[email protected]ea826362012-09-05 23:31:371905
1906 // Disable devtools via policy.
1907 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:091908 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1909 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:301910 std::make_unique<base::Value>(true), nullptr);
[email protected]a1406cb2013-10-16 14:30:431911 content::WindowedNotificationObserver close_observer(
1912 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
[email protected]f77a6522014-05-30 10:55:561913 content::Source<content::WebContents>(
[email protected]d118ad72014-07-21 14:07:011914 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
[email protected]161245d2013-01-09 14:28:111915 UpdateProviderPolicy(policies);
[email protected]a1406cb2013-10-16 14:30:431916 // wait for devtools close
1917 close_observer.Wait();
[email protected]ea826362012-09-05 23:31:371918 // The existing devtools window should have closed.
[email protected]db90e8a2014-07-07 17:57:351919 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
[email protected]ea826362012-09-05 23:31:371920 // And it's not possible to open it again.
1921 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
[email protected]db90e8a2014-07-07 17:57:351922 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
[email protected]ea826362012-09-05 23:31:371923}
1924
Pavol Markodebb0ff2018-05-07 18:35:411925IN_PROC_BROWSER_TEST_F(PolicyTest,
1926 DeveloperToolsDisabledByDeveloperToolsAvailability) {
1927 // Verifies that access to the developer tools can be disabled by setting the
1928 // DeveloperToolsAvailability policy.
1929
1930 // Open devtools.
1931 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1932 content::WebContents* contents =
1933 browser()->tab_strip_model()->GetActiveWebContents();
1934 DevToolsWindow* devtools_window =
1935 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1936 EXPECT_TRUE(devtools_window);
1937
1938 // Disable devtools via policy.
1939 PolicyMap policies;
1940 policies.Set(key::kDeveloperToolsAvailability, POLICY_LEVEL_MANDATORY,
1941 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
1942 std::make_unique<base::Value>(2 /* DeveloperToolsDisallowed */),
1943 nullptr);
1944 content::WindowedNotificationObserver close_observer(
1945 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1946 content::Source<content::WebContents>(
1947 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1948 UpdateProviderPolicy(policies);
1949 // wait for devtools close
1950 close_observer.Wait();
1951 // The existing devtools window should have closed.
1952 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1953 // And it's not possible to open it again.
1954 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1955 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1956}
1957
pmarko6e36b4632016-12-13 17:45:501958namespace {
1959
1960// Utility for waiting until the dev-mode controls are visible/hidden
1961// Uses a MutationObserver on the attributes of the DOM element.
1962void WaitForExtensionsDevModeControlsVisibility(
1963 content::WebContents* contents,
1964 const char* dev_controls_accessor_js,
1965 const char* dev_controls_visibility_check_js,
1966 bool expected_visible) {
1967 bool done = false;
1968 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1969 contents,
1970 base::StringPrintf(
1971 "var screenElement = %s;"
1972 "function SendReplyIfAsExpected() {"
1973 " var is_visible = %s;"
1974 " if (is_visible != %s)"
1975 " return false;"
1976 " observer.disconnect();"
1977 " domAutomationController.send(true);"
1978 " return true;"
1979 "}"
1980 "var observer = new MutationObserver(SendReplyIfAsExpected);"
1981 "if (!SendReplyIfAsExpected()) {"
1982 " var options = { 'attributes': true };"
1983 " observer.observe(screenElement, options);"
1984 "}",
1985 dev_controls_accessor_js,
1986 dev_controls_visibility_check_js,
1987 (expected_visible ? "true" : "false")),
1988 &done));
1989}
1990
1991} // namespace
1992
1993IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabledExtensionsDevMode) {
dpapadd74544f2018-01-22 19:26:031994 // Verifies that when DeveloperToolsDisabled policy is set, the "dev mode"
1995 // in chrome://extensions is actively turned off and the checkbox
1996 // is disabled.
1997 // Note: We don't test the indicator as it is tested in the policy pref test
Pavol Markodebb0ff2018-05-07 18:35:411998 // for kDeveloperToolsDisabled and kDeveloperToolsAvailability.
dpapadd74544f2018-01-22 19:26:031999
2000 // This test depends on the following helper methods to locate the DOM elemens
2001 // to be tested.
2002 const char define_helpers_js[] =
2003 R"(function getToolbar() {
2004 const manager = document.querySelector('extensions-manager');
2005 return manager.$$('extensions-toolbar');
2006 }
2007
2008 function getToggle() {
Esmael El-Moslimany4e9b4a412018-02-26 16:55:162009 return getToolbar().$.devMode;
dpapadd74544f2018-01-22 19:26:032010 }
2011
2012 function getControls() {
Esmael El-Moslimany4e9b4a412018-02-26 16:55:162013 return getToolbar().$.devDrawer;
dpapadd74544f2018-01-22 19:26:032014 }
2015 )";
2016
2017 const char toggle_dev_mode_accessor_js[] = "getToggle()";
2018 const char dev_controls_accessor_js[] = "getControls()";
2019 const char dev_controls_visibility_check_js[] =
2020 "getControls().hasAttribute('expanded')";
2021
2022 // Navigate to the extensions frame and enabled "Developer mode"
2023 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIExtensionsURL));
2024
2025 content::WebContents* contents =
2026 browser()->tab_strip_model()->GetActiveWebContents();
Jialiu Linc534b0d2018-03-01 16:51:522027 EXPECT_TRUE(content::ExecuteScript(contents, std::string(define_helpers_js)));
dpapadd74544f2018-01-22 19:26:032028
2029 EXPECT_TRUE(content::ExecuteScript(
2030 contents, base::StringPrintf("domAutomationController.send(%s.click());",
2031 toggle_dev_mode_accessor_js)));
2032
2033 WaitForExtensionsDevModeControlsVisibility(contents, dev_controls_accessor_js,
2034 dev_controls_visibility_check_js,
2035 true);
2036
2037 // Disable devtools via policy.
2038 PolicyMap policies;
Pavol Markodebb0ff2018-05-07 18:35:412039 policies.Set(key::kDeveloperToolsAvailability, POLICY_LEVEL_MANDATORY,
dpapadd74544f2018-01-22 19:26:032040 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Pavol Markodebb0ff2018-05-07 18:35:412041 std::make_unique<base::Value>(2 /*DeveloperToolsDisallowed*/),
2042 nullptr);
dpapadd74544f2018-01-22 19:26:032043 UpdateProviderPolicy(policies);
2044
2045 // Expect devcontrols to be hidden now...
2046 WaitForExtensionsDevModeControlsVisibility(contents, dev_controls_accessor_js,
2047 dev_controls_visibility_check_js,
2048 false);
2049
2050 // ... and checkbox is disabled
2051 bool is_toggle_dev_mode_checkbox_disabled = false;
2052 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
2053 contents,
2054 base::StringPrintf(
2055 "domAutomationController.send(%s.hasAttribute('disabled'))",
2056 toggle_dev_mode_accessor_js),
2057 &is_toggle_dev_mode_checkbox_disabled));
2058 EXPECT_TRUE(is_toggle_dev_mode_checkbox_disabled);
2059}
2060
[email protected]d1251212012-08-29 13:15:592061IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
2062 // Verifies that the download directory can be forced by policy.
2063
[email protected]d1251212012-08-29 13:15:592064 // Don't prompt for the download location during this test.
2065 browser()->profile()->GetPrefs()->SetBoolean(
2066 prefs::kPromptForDownload, false);
2067
Mattias Nissler441cc652018-04-05 00:08:562068 base::FilePath initial_dir =
2069 DownloadPrefs(browser()->profile()).DownloadPath();
2070
[email protected]d1251212012-08-29 13:15:592071 // Verify that downloads end up on the default directory.
Mattias Nissler441cc652018-04-05 00:08:562072 base::ScopedAllowBlockingForTesting allow_blocking;
[email protected]650b2d52013-02-10 03:41:452073 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
Mattias Nissler441cc652018-04-05 00:08:562074 DownloadAndVerifyFile(browser(), initial_dir, file);
2075 base::DieFileDie(initial_dir.Append(file), false);
[email protected]d1251212012-08-29 13:15:592076
2077 // Override the download directory with the policy and verify a download.
Mattias Nissler441cc652018-04-05 00:08:562078 base::FilePath forced_dir = initial_dir.AppendASCII("forced");
2079
[email protected]d1251212012-08-29 13:15:592080 PolicyMap policies;
jdoerrie122c4da2017-03-06 11:12:042081 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
2082 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Mattias Nissler441cc652018-04-05 00:08:562083 std::make_unique<base::Value>(forced_dir.value()), nullptr);
[email protected]161245d2013-01-09 14:28:112084 UpdateProviderPolicy(policies);
Mattias Nissler441cc652018-04-05 00:08:562085 DownloadAndVerifyFile(browser(), forced_dir, file);
[email protected]d1251212012-08-29 13:15:592086 // Verify that the first download location wasn't affected.
Mattias Nissler441cc652018-04-05 00:08:562087 EXPECT_FALSE(base::PathExists(initial_dir.Append(file)));
[email protected]d1251212012-08-29 13:15:592088}
[email protected]d1251212012-08-29 13:15:592089
Sam McNally5edde0a2019-02-27 11:10:032090#if defined(OS_CHROMEOS)
2091class DrivePolicyTest : public PolicyTest,
2092 public testing::WithParamInterface<bool> {
2093 public:
2094 void SetUpCommandLine(base::CommandLine* command_line) override {
2095 PolicyTest::SetUpCommandLine(command_line);
2096 if (GetParam()) {
2097 scoped_feature_list_.InitAndEnableFeature(chromeos::features::kDriveFs);
2098 } else {
2099 scoped_feature_list_.InitAndDisableFeature(chromeos::features::kDriveFs);
2100 }
2101 }
2102
2103 private:
2104 base::test::ScopedFeatureList scoped_feature_list_;
2105};
2106
2107// Verifies that the download directory can be forced to Google Drive by policy.
2108IN_PROC_BROWSER_TEST_P(DrivePolicyTest, DownloadDirectory_Drive) {
2109 // Override the download directory with the policy.
2110 {
2111 PolicyMap policies;
2112 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_RECOMMENDED,
2113 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2114 std::make_unique<base::Value>("${google_drive}/"), nullptr);
2115 UpdateProviderPolicy(policies);
2116
2117 EXPECT_EQ(drive::DriveIntegrationServiceFactory::FindForProfile(
2118 browser()->profile())
2119 ->GetMountPointPath()
2120 .AppendASCII("root"),
2121 DownloadPrefs(browser()->profile())
2122 .DownloadPath()
2123 .StripTrailingSeparators());
2124 }
2125
2126 PolicyMap policies;
2127 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
2128 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2129 std::make_unique<base::Value>("${google_drive}/Downloads"),
2130 nullptr);
2131 UpdateProviderPolicy(policies);
2132
2133 EXPECT_EQ(drive::DriveIntegrationServiceFactory::FindForProfile(
2134 browser()->profile())
2135 ->GetMountPointPath()
2136 .AppendASCII("root/Downloads"),
2137 DownloadPrefs(browser()->profile())
2138 .DownloadPath()
2139 .StripTrailingSeparators());
2140}
2141
2142INSTANTIATE_TEST_SUITE_P(DrivePolicyTestInstance,
2143 DrivePolicyTest,
2144 testing::Bool());
2145
2146#endif // !defined(OS_CHROMEOS)
2147
[email protected]3b5941412014-08-20 10:54:322148IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
[email protected]ec29ec032012-09-10 18:27:092149 // Verifies that blacklisted extensions can't be installed.
Devlin Cronin2824e9c2018-06-01 23:32:052150 extensions::ExtensionService* service = extension_service();
[email protected]ec29ec032012-09-10 18:27:092151 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
Devlin Cronin5e9387c32018-04-20 04:22:032152 ASSERT_FALSE(service->GetExtensionById(kSimpleWithIconCrxId, true));
[email protected]ec29ec032012-09-10 18:27:092153 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:182154 blacklist.AppendString(kGoodCrxId);
[email protected]ec29ec032012-09-10 18:27:092155 PolicyMap policies;
2156 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092157 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2158 blacklist.CreateDeepCopy(), nullptr);
[email protected]161245d2013-01-09 14:28:112159 UpdateProviderPolicy(policies);
[email protected]ec29ec032012-09-10 18:27:092160
2161 // "good.crx" is blacklisted.
2162 EXPECT_FALSE(InstallExtension(kGoodCrxName));
2163 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2164
Devlin Cronin5e9387c32018-04-20 04:22:032165 // "simple_with_icon.crx" is not.
2166 const extensions::Extension* simple_with_icon =
2167 InstallExtension(kSimpleWithIconCrxName);
2168 ASSERT_TRUE(simple_with_icon);
2169 EXPECT_EQ(kSimpleWithIconCrxId, simple_with_icon->id());
2170 EXPECT_EQ(simple_with_icon,
2171 service->GetExtensionById(kSimpleWithIconCrxId, true));
[email protected]b0aa6ae152013-08-07 09:56:162172}
[email protected]ec29ec032012-09-10 18:27:092173
Christopher Lam96b044c2017-11-24 03:29:462174// Ensure that bookmark apps are not blocked by the ExtensionInstallBlacklist
2175// policy.
2176IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklist_BookmarkApp) {
2177 const extensions::Extension* bookmark_app = InstallBookmarkApp();
2178 ASSERT_TRUE(bookmark_app);
2179 EXPECT_TRUE(InstallExtension(kGoodCrxName));
2180
Devlin Cronin2824e9c2018-06-01 23:32:052181 extensions::ExtensionService* service = extension_service();
Christopher Lam96b044c2017-11-24 03:29:462182 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
2183 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2184
2185 // Now set ExtensionInstallBlacklist policy to block all extensions.
2186 PolicyMap policies;
2187 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
2188 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2189 extensions::ListBuilder().Append("*").Build(), nullptr);
2190 UpdateProviderPolicy(policies);
2191
2192 // The bookmark app should still be enabled, with |kGoodCrxId| being disabled.
2193 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
2194 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2195}
2196
Kyle Spiersa3b18452019-05-07 16:07:092197// Ensure that when INSTALLATION_REMOVED is set
Kyle Spiersbb4b9f5f52019-05-02 17:17:152198// that blacklisted extensions are removed from the device.
2199IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallRemovedPolicy) {
2200 EXPECT_TRUE(InstallExtension(kGoodCrxName));
2201
2202 extensions::ExtensionService* service = extension_service();
2203 EXPECT_TRUE(service->GetInstalledExtension(kGoodCrxId));
2204
2205 // Should uninstall good_v1.crx.
2206 base::DictionaryValue dict_value;
2207 dict_value.SetString(std::string(kGoodCrxId) + "." +
2208 extensions::schema_constants::kInstallationMode,
2209 extensions::schema_constants::kRemoved);
2210 PolicyMap policies;
2211 policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
2212 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2213 dict_value.CreateDeepCopy(), nullptr);
2214 extensions::TestExtensionRegistryObserver observer(
2215 extensions::ExtensionRegistry::Get(browser()->profile()));
2216 UpdateProviderPolicy(policies);
2217 observer.WaitForExtensionUnloaded();
2218
2219 EXPECT_FALSE(service->GetInstalledExtension(kGoodCrxId));
2220}
2221
Kyle Spiers42145b72019-06-19 20:32:282222// Ensure that when INSTALLATION_REMOVED is set for wildcard
2223// that blacklisted extensions are removed from the device.
2224IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionWildcardRemovedPolicy) {
2225 EXPECT_TRUE(InstallExtension(kGoodCrxName));
2226
2227 extensions::ExtensionService* service = extension_service();
2228 EXPECT_TRUE(service->GetInstalledExtension(kGoodCrxId));
2229
2230 // Should uninstall good_v1.crx.
2231 base::DictionaryValue dict_value;
2232 dict_value.SetString(
2233 std::string("*") + "." + extensions::schema_constants::kInstallationMode,
2234 extensions::schema_constants::kRemoved);
2235 PolicyMap policies;
2236 policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
2237 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2238 dict_value.CreateDeepCopy(), nullptr);
2239 extensions::TestExtensionRegistryObserver observer(
2240 extensions::ExtensionRegistry::Get(browser()->profile()));
2241 UpdateProviderPolicy(policies);
2242 observer.WaitForExtensionUnloaded();
2243
2244 EXPECT_FALSE(service->GetInstalledExtension(kGoodCrxId));
2245}
2246
Christopher Lam96b044c2017-11-24 03:29:462247// Ensure that bookmark apps are not blocked by the ExtensionAllowedTypes
2248// policy.
2249IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes_BookmarkApp) {
2250 const extensions::Extension* bookmark_app = InstallBookmarkApp();
2251 ASSERT_TRUE(bookmark_app);
2252 EXPECT_TRUE(InstallExtension(kGoodCrxName));
2253
Devlin Cronin2824e9c2018-06-01 23:32:052254 extensions::ExtensionService* service = extension_service();
Christopher Lam96b044c2017-11-24 03:29:462255 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
2256 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2257
2258 // Now set policy to only allow themes. Note: Bookmark apps are hosted
2259 // apps.
2260 PolicyMap policies;
2261 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
2262 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2263 extensions::ListBuilder().Append("theme").Build(), nullptr);
2264 UpdateProviderPolicy(policies);
2265
2266 // The bookmark app should still be enabled, with |kGoodCrxId| being disabled.
2267 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
2268 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2269}
2270
2271// Ensure that bookmark apps are not blocked by the ExtensionSettings
2272// policy.
2273IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionSettings_BookmarkApp) {
2274 const extensions::Extension* bookmark_app = InstallBookmarkApp();
2275 ASSERT_TRUE(bookmark_app);
2276 EXPECT_TRUE(InstallExtension(kGoodCrxName));
2277
Devlin Cronin2824e9c2018-06-01 23:32:052278 extensions::ExtensionService* service = extension_service();
Christopher Lam96b044c2017-11-24 03:29:462279 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
2280 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2281
2282 // Now set policy to block all extensions.
2283 PolicyMap policies;
2284 policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
2285 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2286 extensions::DictionaryBuilder()
2287 .Set("*", extensions::DictionaryBuilder()
2288 .Set("installation_mode", "blocked")
2289 .Build())
2290 .Build(),
2291 nullptr);
2292 UpdateProviderPolicy(policies);
2293
2294 // The bookmark app should still be enabled, with |kGoodCrxId| being disabled.
2295 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
2296 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2297
2298 // Clear all policies.
2299 policies.Clear();
2300 UpdateProviderPolicy(policies);
2301
2302 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
2303 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2304
2305 // Now set policy to only allow themes. Note: Bookmark apps are hosted
2306 // apps.
2307 policies.Set(
2308 key::kExtensionSettings, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2309 POLICY_SOURCE_CLOUD,
2310 extensions::DictionaryBuilder()
2311 .Set("*", extensions::DictionaryBuilder()
2312 .Set("allowed_types",
2313 extensions::ListBuilder().Append("theme").Build())
2314 .Build())
2315 .Build(),
2316 nullptr);
2317 UpdateProviderPolicy(policies);
2318
2319 // The bookmark app should still be enabled, with |kGoodCrxId| being disabled.
2320 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
2321 EXPECT_TRUE(service->IsExtensionEnabled(bookmark_app->id()));
2322}
2323
[email protected]72ba2eb2013-10-16 16:06:472324// Flaky on windows; http://crbug.com/307994.
2325#if defined(OS_WIN)
2326#define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
2327#else
2328#define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
2329#endif
2330IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
[email protected]b0aa6ae152013-08-07 09:56:162331 // Verify that a wildcard blacklist takes effect.
Devlin Cronin5e9387c32018-04-20 04:22:032332 EXPECT_TRUE(InstallExtension(kSimpleWithIconCrxName));
Devlin Cronin2824e9c2018-06-01 23:32:052333 extensions::ExtensionService* service = extension_service();
[email protected]b0aa6ae152013-08-07 09:56:162334 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
Devlin Cronin5e9387c32018-04-20 04:22:032335 ASSERT_TRUE(service->GetExtensionById(kSimpleWithIconCrxId, true));
[email protected]b0aa6ae152013-08-07 09:56:162336 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:182337 blacklist.AppendString("*");
[email protected]b0aa6ae152013-08-07 09:56:162338 PolicyMap policies;
[email protected]ec29ec032012-09-10 18:27:092339 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092340 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2341 blacklist.CreateDeepCopy(), nullptr);
[email protected]161245d2013-01-09 14:28:112342 UpdateProviderPolicy(policies);
[email protected]b0aa6ae152013-08-07 09:56:162343
Devlin Cronin5e9387c32018-04-20 04:22:032344 // "simple_with_icon" should be disabled.
2345 EXPECT_TRUE(service->GetExtensionById(kSimpleWithIconCrxId, true));
2346 EXPECT_FALSE(service->IsExtensionEnabled(kSimpleWithIconCrxId));
[email protected]b0aa6ae152013-08-07 09:56:162347
Devlin Cronin5e9387c32018-04-20 04:22:032348 // It shouldn't be possible to re-enable "simple_with_icon", until it
2349 // satisfies management policy.
2350 service->EnableExtension(kSimpleWithIconCrxId);
2351 EXPECT_FALSE(service->IsExtensionEnabled(kSimpleWithIconCrxId));
Karan Bhatia2a117232017-08-23 00:24:562352
2353 // It shouldn't be possible to install good.crx.
[email protected]ec29ec032012-09-10 18:27:092354 EXPECT_FALSE(InstallExtension(kGoodCrxName));
2355 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2356}
2357
joaodasilva30c8be92014-10-23 23:40:412358IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSharedModules) {
2359 // Verifies that shared_modules are not affected by the blacklist.
2360
Yuzhu Shenf3c2fcc2017-11-30 20:30:222361 base::FilePath base_path;
2362 GetTestDataDirectory(&base_path);
2363 base::FilePath update_xml_template_path =
2364 base_path.Append(kTestExtensionsDir)
2365 .AppendASCII("policy_shared_module")
2366 .AppendASCII("update_template.xml");
2367
2368 std::string update_xml_path =
2369 "/" + base::FilePath(kTestExtensionsDir).MaybeAsASCII() +
2370 "/policy_shared_module/gen_update.xml";
2371 RegisterURLReplacingHandler(embedded_test_server(), update_xml_path,
2372 update_xml_template_path);
2373 ASSERT_TRUE(embedded_test_server()->Start());
2374
joaodasilva30c8be92014-10-23 23:40:412375 const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
2376 const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";
2377
2378 // Make sure that "import" and "export" are available to these extension IDs
2379 // by mocking the release channel.
sdefresne6e883e42015-07-30 08:05:542380 extensions::ScopedCurrentChannel channel(version_info::Channel::DEV);
joaodasilva30c8be92014-10-23 23:40:412381
2382 // Verify that the extensions are not installed initially.
Devlin Cronin2824e9c2018-06-01 23:32:052383 extensions::ExtensionService* service = extension_service();
joaodasilva30c8be92014-10-23 23:40:412384 ASSERT_FALSE(service->GetExtensionById(kImporterId, true));
2385 ASSERT_FALSE(service->GetExtensionById(kSharedModuleId, true));
2386
2387 // Mock the webstore update URL. This is where the shared module extension
2388 // will be installed from.
Yuzhu Shenf3c2fcc2017-11-30 20:30:222389 GURL update_xml_url = embedded_test_server()->GetURL(update_xml_path);
Konstantin Ganenkoae1129c2017-09-15 16:28:592390 extension_test_util::SetGalleryUpdateURL(update_xml_url);
joaodasilva30c8be92014-10-23 23:40:412391 ui_test_utils::NavigateToURL(browser(), update_xml_url);
2392
2393 // Blacklist "*" but force-install the importer extension. The shared module
2394 // should be automatically installed too.
2395 base::ListValue blacklist;
2396 blacklist.AppendString("*");
2397 base::ListValue forcelist;
2398 forcelist.AppendString(
2399 base::StringPrintf("%s;%s", kImporterId, update_xml_url.spec().c_str()));
2400 PolicyMap policies;
2401 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092402 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2403 blacklist.CreateDeepCopy(), nullptr);
joaodasilva30c8be92014-10-23 23:40:412404 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092405 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2406 forcelist.CreateDeepCopy(), nullptr);
joaodasilva30c8be92014-10-23 23:40:412407
2408 extensions::ExtensionRegistry* registry =
2409 extensions::ExtensionRegistry::Get(browser()->profile());
2410 extensions::TestExtensionRegistryObserver observe_importer(
2411 registry, kImporterId);
2412 extensions::TestExtensionRegistryObserver observe_shared_module(
2413 registry, kSharedModuleId);
2414 UpdateProviderPolicy(policies);
2415 observe_importer.WaitForExtensionLoaded();
2416 observe_shared_module.WaitForExtensionLoaded();
2417
2418 // Verify that both extensions got installed.
2419 const extensions::Extension* importer =
2420 service->GetExtensionById(kImporterId, true);
2421 ASSERT_TRUE(importer);
2422 EXPECT_EQ(kImporterId, importer->id());
2423 const extensions::Extension* shared_module =
2424 service->GetExtensionById(kSharedModuleId, true);
2425 ASSERT_TRUE(shared_module);
2426 EXPECT_EQ(kSharedModuleId, shared_module->id());
2427 EXPECT_TRUE(shared_module->is_shared_module());
2428
2429 // Verify the dependency.
dcheng08cfe9ba2016-04-14 17:46:452430 std::unique_ptr<extensions::ExtensionSet> set =
joaodasilva30c8be92014-10-23 23:40:412431 service->shared_module_service()->GetDependentExtensions(shared_module);
2432 ASSERT_TRUE(set);
2433 EXPECT_EQ(1u, set->size());
2434 EXPECT_TRUE(set->Contains(importer->id()));
2435
2436 std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
2437 extensions::SharedModuleInfo::GetImports(importer);
2438 ASSERT_EQ(1u, imports.size());
2439 EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
2440}
2441
[email protected]ec29ec032012-09-10 18:27:092442IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
2443 // Verifies that the whitelist can open exceptions to the blacklist.
Devlin Cronin2824e9c2018-06-01 23:32:052444 extensions::ExtensionService* service = extension_service();
[email protected]ec29ec032012-09-10 18:27:092445 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
Devlin Cronin5e9387c32018-04-20 04:22:032446 ASSERT_FALSE(service->GetExtensionById(kSimpleWithIconCrxId, true));
[email protected]ec29ec032012-09-10 18:27:092447 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:182448 blacklist.AppendString("*");
[email protected]ec29ec032012-09-10 18:27:092449 base::ListValue whitelist;
dchengd9ea63862016-06-03 02:27:182450 whitelist.AppendString(kGoodCrxId);
[email protected]ec29ec032012-09-10 18:27:092451 PolicyMap policies;
2452 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092453 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2454 blacklist.CreateDeepCopy(), nullptr);
[email protected]ec29ec032012-09-10 18:27:092455 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092456 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2457 whitelist.CreateDeepCopy(), nullptr);
[email protected]161245d2013-01-09 14:28:112458 UpdateProviderPolicy(policies);
Devlin Cronin5e9387c32018-04-20 04:22:032459 // "simple_with_icon.crx" is blacklisted.
2460 EXPECT_FALSE(InstallExtension(kSimpleWithIconCrxName));
2461 EXPECT_FALSE(service->GetExtensionById(kSimpleWithIconCrxId, true));
[email protected]ec29ec032012-09-10 18:27:092462 // "good.crx" has a whitelist exception.
2463 const extensions::Extension* good = InstallExtension(kGoodCrxName);
2464 ASSERT_TRUE(good);
2465 EXPECT_EQ(kGoodCrxId, good->id());
2466 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
2467 // The user can also remove this extension.
2468 UninstallExtension(kGoodCrxId, true);
2469}
2470
John Abd-El-Malek580bc96a52018-08-10 02:24:472471namespace {
2472
2473class ExtensionRequestInterceptor {
2474 public:
2475 ExtensionRequestInterceptor()
2476 : interceptor_(
2477 base::BindRepeating(&ExtensionRequestInterceptor::OnRequest,
2478 base::Unretained(this))) {}
2479
2480 void set_interceptor_hook(
2481 content::URLLoaderInterceptor::InterceptCallback callback) {
2482 callback_ = std::move(callback);
2483 }
2484
2485 private:
2486 bool OnRequest(content::URLLoaderInterceptor::RequestParams* params) {
2487 if (callback_ && callback_.Run(params))
2488 return true;
2489 // Mock out requests to the Web Store.
2490 if (params->url_request.url.host() == "clients2.google.com" &&
2491 params->url_request.url.path() == "/service/update2/crx") {
2492 content::URLLoaderInterceptor::WriteResponse(
2493 "chrome/test/data/extensions/good2_update_manifest.xml",
2494 params->client.get());
2495 return true;
2496 }
2497
2498 if (params->url_request.url.path() == "/good_update_manifest.xml") {
2499 content::URLLoaderInterceptor::WriteResponse(
2500 "chrome/test/data/extensions/good2_update_manifest.xml",
2501 params->client.get());
2502 return true;
2503 }
2504 if (params->url_request.url.path() == "/extensions/good_v1.crx") {
2505 content::URLLoaderInterceptor::WriteResponse(
2506 "chrome/test/data/extensions/good_v1.crx", params->client.get());
2507 return true;
2508 }
2509 if (params->url_request.url.path() == "/extensions/good2.crx") {
2510 content::URLLoaderInterceptor::WriteResponse(
2511 "chrome/test/data/extensions/good2.crx", params->client.get());
2512 return true;
2513 }
2514
2515 return false;
2516 }
2517
2518 content::URLLoaderInterceptor::InterceptCallback callback_;
2519 content::URLLoaderInterceptor interceptor_;
2520};
2521
2522} // namespace
2523
[email protected]ec29ec032012-09-10 18:27:092524IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
2525 // Verifies that extensions that are force-installed by policies are
2526 // installed and can't be uninstalled.
Maksim Ivanoveaac2ff2018-04-16 16:23:242527
John Abd-El-Malek580bc96a52018-08-10 02:24:472528 ExtensionRequestInterceptor interceptor;
2529
Devlin Cronin2824e9c2018-06-01 23:32:052530 extensions::ExtensionService* service = extension_service();
[email protected]ec29ec032012-09-10 18:27:092531 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2532
2533 // Extensions that are force-installed come from an update URL, which defaults
John Abd-El-Malek580bc96a52018-08-10 02:24:472534 // to the webstore. Use a test URL for this test with an update manifest
[email protected]6b6a6e62013-05-28 19:33:372535 // that includes "good_v1.crx".
John Abd-El-Malek580bc96a52018-08-10 02:24:472536 ASSERT_TRUE(embedded_test_server()->Start());
2537 GURL url =
2538 embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");
[email protected]ec29ec032012-09-10 18:27:092539
[email protected]6b6a6e62013-05-28 19:33:372540 // Setting the forcelist extension should install "good_v1.crx".
[email protected]ec29ec032012-09-10 18:27:092541 base::ListValue forcelist;
dchengd9ea63862016-06-03 02:27:182542 forcelist.AppendString(
2543 base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str()));
[email protected]ec29ec032012-09-10 18:27:092544 PolicyMap policies;
2545 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092546 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2547 forcelist.CreateDeepCopy(), nullptr);
limasdf8fec6612015-10-12 10:03:062548 extensions::TestExtensionRegistryObserver observer(
2549 extensions::ExtensionRegistry::Get(browser()->profile()));
[email protected]161245d2013-01-09 14:28:112550 UpdateProviderPolicy(policies);
limasdf8fec6612015-10-12 10:03:062551 observer.WaitForExtensionWillBeInstalled();
[email protected]41bb80bd2013-05-03 10:56:022552 // Note: Cannot check that the notification details match the expected
2553 // exception, since the details object has already been freed prior to
limasdf8fec6612015-10-12 10:03:062554 // the completion of observer.WaitForExtensionWillBeInstalled().
[email protected]41bb80bd2013-05-03 10:56:022555
2556 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
2557
[email protected]ec29ec032012-09-10 18:27:092558 // The user is not allowed to uninstall force-installed extensions.
2559 UninstallExtension(kGoodCrxId, false);
[email protected]ec1b3e712013-05-25 14:29:162560
limasdfc83e0b72017-03-03 17:08:352561 scoped_refptr<extensions::UnpackedInstaller> installer =
2562 extensions::UnpackedInstaller::Create(extension_service());
2563
[email protected]ec1b3e712013-05-25 14:29:162564 // The user is not allowed to load an unpacked extension with the
2565 // same ID as a force-installed extension.
limasdfc83e0b72017-03-03 17:08:352566 base::FilePath good_extension_path(ui_test_utils::GetTestFilePath(
Devlin Cronin19775cc2018-04-19 15:04:262567 base::FilePath(kTestExtensionsDir), base::FilePath(kSimpleWithPopupExt)));
limasdfc83e0b72017-03-03 17:08:352568 content::WindowedNotificationObserver extension_load_error_observer(
2569 extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
2570 content::NotificationService::AllSources());
2571 installer->Load(good_extension_path);
2572 extension_load_error_observer.Wait();
[email protected]ec1b3e712013-05-25 14:29:162573
2574 // Loading other unpacked extensions are not blocked.
limasdfc83e0b72017-03-03 17:08:352575 scoped_refptr<const extensions::Extension> extension =
2576 LoadUnpackedExtension(kAppUnpackedExt);
2577 ASSERT_TRUE(extension);
[email protected]6b6a6e62013-05-28 19:33:372578
2579 const std::string old_version_number =
Devlin Cronin03bf2d22017-12-20 08:21:052580 service->GetExtensionById(kGoodCrxId, true)->version().GetString();
[email protected]6b6a6e62013-05-28 19:33:372581
John Abd-El-Malek580bc96a52018-08-10 02:24:472582 content::WindowedNotificationObserver new_process_observer(
2583 content::NOTIFICATION_RENDERER_PROCESS_CREATED,
2584 content::NotificationService::AllSources());
[email protected]6b6a6e62013-05-28 19:33:372585
2586 // Updating the force-installed extension.
2587 extensions::ExtensionUpdater* updater = service->updater();
2588 extensions::ExtensionUpdater::CheckParams params;
2589 params.install_immediately = true;
limasdf8fec6612015-10-12 10:03:062590 extensions::TestExtensionRegistryObserver update_observer(
2591 extensions::ExtensionRegistry::Get(browser()->profile()));
Minh X. Nguyen722b9682018-04-25 21:46:482592 updater->CheckNow(std::move(params));
limasdf8fec6612015-10-12 10:03:062593 update_observer.WaitForExtensionWillBeInstalled();
[email protected]6b6a6e62013-05-28 19:33:372594
Devlin Cronin03bf2d22017-12-20 08:21:052595 const base::Version& new_version =
[email protected]6b6a6e62013-05-28 19:33:372596 service->GetExtensionById(kGoodCrxId, true)->version();
Devlin Cronin03bf2d22017-12-20 08:21:052597 ASSERT_TRUE(new_version.IsValid());
[email protected]6b6a6e62013-05-28 19:33:372598 base::Version old_version(old_version_number);
2599 ASSERT_TRUE(old_version.IsValid());
2600
Devlin Cronin03bf2d22017-12-20 08:21:052601 EXPECT_EQ(1, new_version.CompareTo(old_version));
[email protected]6b6a6e62013-05-28 19:33:372602
John Abd-El-Malek580bc96a52018-08-10 02:24:472603 // Wait for the new extension process to launch.
2604 new_process_observer.Wait();
[email protected]6b9dafc2013-08-30 15:41:592605
2606 // Wait until any background pages belonging to force-installed extensions
2607 // have been loaded.
[email protected]98b6d942013-11-10 00:34:072608 extensions::ProcessManager* manager =
reillyg0ea3fa902014-10-28 15:30:232609 extensions::ProcessManager::Get(browser()->profile());
rdevlin.cronin6ae04a012015-04-03 20:19:402610 extensions::ProcessManager::FrameSet all_frames = manager->GetAllFrames();
jdoerrie601c7152018-10-02 23:43:112611 for (auto iter = all_frames.begin(); iter != all_frames.end();) {
rdevlin.cronin6ae04a012015-04-03 20:19:402612 content::WebContents* web_contents =
2613 content::WebContents::FromRenderFrameHost(*iter);
2614 ASSERT_TRUE(web_contents);
2615 if (!web_contents->IsLoading()) {
[email protected]6b9dafc2013-08-30 15:41:592616 ++iter;
2617 } else {
[email protected]1eb39642013-10-17 22:06:532618 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
[email protected]6b9dafc2013-08-30 15:41:592619
2620 // Test activity may have modified the set of extension processes during
2621 // message processing, so re-start the iteration to catch added/removed
2622 // processes.
rdevlin.cronin6ae04a012015-04-03 20:19:402623 all_frames = manager->GetAllFrames();
2624 iter = all_frames.begin();
[email protected]6b9dafc2013-08-30 15:41:592625 }
2626 }
2627
2628 // Test policy-installed extensions are reloaded when killed.
Lukasz Anforowicz907b6ac2019-06-13 01:49:082629 {
Lukasz Anforowicz907b6ac2019-06-13 01:49:082630 BackgroundContentsService::
2631 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
2632 content::WindowedNotificationObserver extension_crashed_observer(
2633 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
2634 content::NotificationService::AllSources());
2635 extensions::TestExtensionRegistryObserver extension_loaded_observer(
2636 extensions::ExtensionRegistry::Get(browser()->profile()), kGoodCrxId);
2637 extensions::ExtensionHost* extension_host =
2638 extensions::ProcessManager::Get(browser()->profile())
2639 ->GetBackgroundHostForExtension(kGoodCrxId);
Lukasz Anforowiczd97bc0ec2019-06-19 23:58:222640 content::RenderProcessHost* process = extension_host->render_process_host();
2641 content::ScopedAllowRendererCrashes allow_renderer_crashes(process);
2642 process->Shutdown(content::RESULT_CODE_KILLED);
Lukasz Anforowicz907b6ac2019-06-13 01:49:082643 extension_crashed_observer.Wait();
2644 extension_loaded_observer.WaitForExtensionLoaded();
2645 }
[email protected]ec29ec032012-09-10 18:27:092646}
2647
Maksim Ivanoveaac2ff2018-04-16 16:23:242648IN_PROC_BROWSER_TEST_F(PolicyTest,
2649 ExtensionInstallForcelist_DefaultedUpdateUrl) {
2650 // Verifies the ExtensionInstallForcelist policy with an empty (defaulted)
2651 // "update" URL.
2652
John Abd-El-Malek580bc96a52018-08-10 02:24:472653 ExtensionRequestInterceptor interceptor;
2654
Devlin Cronin2824e9c2018-06-01 23:32:052655 extensions::ExtensionService* service = extension_service();
Maksim Ivanoveaac2ff2018-04-16 16:23:242656 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2657
Maksim Ivanoveaac2ff2018-04-16 16:23:242658 // Setting the forcelist extension should install "good_v1.crx".
2659 base::ListValue forcelist;
2660 forcelist.AppendString(kGoodCrxId);
2661 PolicyMap policies;
2662 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
2663 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2664 forcelist.CreateDeepCopy(), nullptr);
2665 extensions::TestExtensionRegistryObserver observer(
2666 extensions::ExtensionRegistry::Get(browser()->profile()));
2667 UpdateProviderPolicy(policies);
2668 observer.WaitForExtensionWillBeInstalled();
2669
Maksim Ivanoveaac2ff2018-04-16 16:23:242670 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
2671}
2672
binjincccacef2014-10-13 19:00:202673IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
2674 // Verifies that extensions that are recommended-installed by policies are
2675 // installed, can be disabled but not uninstalled.
Nick Petersond952cb772018-03-07 15:46:032676
John Abd-El-Malek580bc96a52018-08-10 02:24:472677 ExtensionRequestInterceptor interceptor;
2678
2679 // Extensions that are force-installed come from an update URL, which defaults
2680 // to the webstore. Use a test URL for this test with an update manifest
2681 // that includes "good_v1.crx".
John Abd-El-Malek580bc96a52018-08-10 02:24:472682 ASSERT_TRUE(embedded_test_server()->Start());
2683 GURL url =
2684 embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");
2685
Nick Petersond952cb772018-03-07 15:46:032686// Mark as enterprise managed.
2687#if defined(OS_WIN)
Roger Tawac1b544a82018-08-24 16:23:252688 base::win::ScopedDomainStateForTesting scoped_domain(true);
Nick Petersond952cb772018-03-07 15:46:032689#endif
2690
Devlin Cronin2824e9c2018-06-01 23:32:052691 extensions::ExtensionService* service = extension_service();
binjincccacef2014-10-13 19:00:202692 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2693
binjincccacef2014-10-13 19:00:202694 // Setting the forcelist extension should install "good_v1.crx".
2695 base::DictionaryValue dict_value;
2696 dict_value.SetString(std::string(kGoodCrxId) + "." +
2697 extensions::schema_constants::kInstallationMode,
2698 extensions::schema_constants::kNormalInstalled);
2699 dict_value.SetString(
2700 std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
2701 url.spec());
2702 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:092703 policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
2704 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2705 dict_value.CreateDeepCopy(), nullptr);
limasdf8fec6612015-10-12 10:03:062706 extensions::TestExtensionRegistryObserver observer(
2707 extensions::ExtensionRegistry::Get(browser()->profile()));
binjincccacef2014-10-13 19:00:202708 UpdateProviderPolicy(policies);
limasdf8fec6612015-10-12 10:03:062709 observer.WaitForExtensionWillBeInstalled();
binjincccacef2014-10-13 19:00:202710
2711 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
2712
2713 // The user is not allowed to uninstall recommended-installed extensions.
2714 UninstallExtension(kGoodCrxId, false);
2715
2716 // Explictly re-enables the extension.
2717 service->EnableExtension(kGoodCrxId);
2718
2719 // But the user is allowed to disable them.
2720 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
2721 DisableExtension(kGoodCrxId);
2722 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
2723}
2724
Pavol Marko81e69712019-02-22 15:19:232725IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
[email protected]ce4e5d7a2012-12-11 20:59:262726 // Verifies that extensions are blocked if policy specifies an allowed types
2727 // list and the extension's type is not on that list.
Devlin Cronin2824e9c2018-06-01 23:32:052728 extensions::ExtensionService* service = extension_service();
[email protected]ce4e5d7a2012-12-11 20:59:262729 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2730 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
2731
2732 base::ListValue allowed_types;
2733 allowed_types.AppendString("hosted_app");
2734 PolicyMap policies;
2735 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:092736 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
2737 allowed_types.CreateDeepCopy(), nullptr);
[email protected]161245d2013-01-09 14:28:112738 UpdateProviderPolicy(policies);
[email protected]ce4e5d7a2012-12-11 20:59:262739
2740 // "good.crx" is blocked.
2741 EXPECT_FALSE(InstallExtension(kGoodCrxName));
2742 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
2743
2744 // "hosted_app.crx" is of a whitelisted type.
2745 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
2746 ASSERT_TRUE(hosted_app);
2747 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
2748 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
2749
2750 // The user can remove the extension.
2751 UninstallExtension(kHostedAppCrxId, true);
2752}
2753
[email protected]8967816d2013-03-26 12:58:252754// Checks that a click on an extension CRX download triggers the extension
2755// installation prompt without further user interaction when the source is
2756// whitelisted by policy.
[email protected]2107935b2013-09-20 16:41:462757// Flaky on windows; http://crbug.com/295729 .
2758#if defined(OS_WIN)
2759#define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
2760#else
2761#define MAYBE_ExtensionInstallSources ExtensionInstallSources
2762#endif
2763IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
rdevlin.cronin66209492015-06-10 20:44:052764 extensions::ScopedTestDialogAutoConfirm auto_confirm(
2765 extensions::ScopedTestDialogAutoConfirm::ACCEPT);
Devlin Cronin5e9387c32018-04-20 04:22:032766 extensions::ScopedInstallVerifierBypassForTest install_verifier_bypass;
[email protected]8967816d2013-03-26 12:58:252767
John Abd-El-Malek9db74cc62018-08-08 19:25:212768 ASSERT_TRUE(embedded_test_server()->Start());
[email protected]8967816d2013-03-26 12:58:252769
John Abd-El-Malek9db74cc62018-08-08 19:25:212770 GURL download_page_url = embedded_test_server()->GetURL(
2771 "/policy/extension_install_sources_test.html");
[email protected]8967816d2013-03-26 12:58:252772 ui_test_utils::NavigateToURL(browser(), download_page_url);
2773
John Abd-El-Malek9db74cc62018-08-08 19:25:212774 const GURL install_source_url(
2775 embedded_test_server()->GetURL("/extensions/*"));
2776 const GURL referrer_url(embedded_test_server()->GetURL("/policy/*"));
2777
[email protected]8967816d2013-03-26 12:58:252778 // As long as the policy is not present, extensions are considered dangerous.
2779 content::DownloadTestObserverTerminal download_observer(
2780 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
2781 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
2782 PerformClick(0, 0);
2783 download_observer.WaitForFinished();
2784
2785 // Install the policy and trigger another download.
2786 base::ListValue install_sources;
2787 install_sources.AppendString(install_source_url.spec());
2788 install_sources.AppendString(referrer_url.spec());
2789 PolicyMap policies;
2790 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
fhorschig64834b712015-09-21 14:20:232791 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
dcheng3b344bc22016-05-10 02:26:092792 install_sources.CreateDeepCopy(), nullptr);
[email protected]8967816d2013-03-26 12:58:252793 UpdateProviderPolicy(policies);
2794
limasdf8fec6612015-10-12 10:03:062795 extensions::TestExtensionRegistryObserver observer(
2796 extensions::ExtensionRegistry::Get(browser()->profile()));
[email protected]8967816d2013-03-26 12:58:252797 PerformClick(1, 0);
limasdf8fec6612015-10-12 10:03:062798 observer.WaitForExtensionWillBeInstalled();
[email protected]41bb80bd2013-05-03 10:56:022799 // Note: Cannot check that the notification details match the expected
2800 // exception, since the details object has already been freed prior to
limasdf8fec6612015-10-12 10:03:062801 // the completion of observer.WaitForExtensionWillBeInstalled().
[email protected]8967816d2013-03-26 12:58:252802
2803 // The first extension shouldn't be present, the second should be there.
2804 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
Devlin Cronin5e9387c32018-04-20 04:22:032805 EXPECT_TRUE(
2806 extension_service()->GetExtensionById(kSimpleWithIconCrxId, false));
[email protected]8967816d2013-03-26 12:58:252807}
2808
binjin8e3d0182014-12-04 16:44:282809// Verifies that extensions with version older than the minimum version required
2810// by policy will get disabled, and will be auto-updated and/or re-enabled upon
2811// policy changes as well as regular auto-updater scheduled updates.
2812IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequired) {
John Abd-El-Malek580bc96a52018-08-10 02:24:472813 ExtensionRequestInterceptor interceptor;
2814
2815 base::AtomicRefCount update_extension_count;
2816 base::RunLoop first_update_extension_runloop;
2817 interceptor.set_interceptor_hook(base::BindLambdaForTesting(
2818 [&](content::URLLoaderInterceptor::RequestParams* params) {
2819 if (params->url_request.url.host() != "update.extension")
2820 return false;
2821
2822 if (!update_extension_count.IsZero() && !update_extension_count.IsOne())
2823 return false;
2824
2825 if (update_extension_count.IsZero()) {
2826 content::URLLoaderInterceptor::WriteResponse(
2827 "400 Bad request", std::string(), params->client.get());
2828 } else {
2829 content::URLLoaderInterceptor::WriteResponse(
2830 "chrome/test/data/extensions/good2_update_manifest.xml",
2831 params->client.get());
2832 }
2833 if (update_extension_count.IsZero())
2834 first_update_extension_runloop.Quit();
2835 update_extension_count.Increment();
2836 return true;
2837 }));
2838
Devlin Cronin2824e9c2018-06-01 23:32:052839 extensions::ExtensionService* service = extension_service();
binjin8e3d0182014-12-04 16:44:282840 extensions::ExtensionRegistry* registry =
2841 extensions::ExtensionRegistry::Get(browser()->profile());
2842 extensions::ExtensionPrefs* extension_prefs =
2843 extensions::ExtensionPrefs::Get(browser()->profile());
2844
binjin8e3d0182014-12-04 16:44:282845 // Install the extension.
2846 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
2847 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2848
2849 // Update policy to set a minimum version of 1.0.0.0, the extension (with
2850 // version 1.0.0.0) should still be enabled.
2851 {
2852 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2853 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.0");
2854 }
2855 base::RunLoop().RunUntilIdle();
2856
2857 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2858
2859 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2860 // version 1.0.0.0) should now be disabled.
John Abd-El-Malek580bc96a52018-08-10 02:24:472861 EXPECT_TRUE(update_extension_count.IsZero());
binjin8e3d0182014-12-04 16:44:282862 {
2863 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2864 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2865 }
John Abd-El-Malek580bc96a52018-08-10 02:24:472866 first_update_extension_runloop.Run();
2867 EXPECT_TRUE(update_extension_count.IsOne());
binjin8e3d0182014-12-04 16:44:282868
2869 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
Minh X. Nguyen45479012017-08-18 21:35:362870 EXPECT_EQ(extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY,
binjin8e3d0182014-12-04 16:44:282871 extension_prefs->GetDisableReasons(kGoodCrxId));
2872
2873 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2874 // via the update URL in the manifest of the older version.
John Abd-El-Malek580bc96a52018-08-10 02:24:472875 EXPECT_TRUE(update_extension_count.IsOne());
binjin8e3d0182014-12-04 16:44:282876 {
limasdf8fec6612015-10-12 10:03:062877 extensions::TestExtensionRegistryObserver update_observer(
2878 extensions::ExtensionRegistry::Get(browser()->profile()));
binjin8e3d0182014-12-04 16:44:282879 service->updater()->CheckSoon();
limasdf8fec6612015-10-12 10:03:062880 update_observer.WaitForExtensionWillBeInstalled();
binjin8e3d0182014-12-04 16:44:282881 }
John Abd-El-Malek580bc96a52018-08-10 02:24:472882 EXPECT_EQ(2, update_extension_count.SubtleRefCountForDebug());
binjin8e3d0182014-12-04 16:44:282883
2884 // The extension should be auto-updated to newer version and re-enabled.
2885 EXPECT_EQ("1.0.0.1",
Devlin Cronin03bf2d22017-12-20 08:21:052886 service->GetInstalledExtension(kGoodCrxId)->version().GetString());
binjin8e3d0182014-12-04 16:44:282887 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2888}
2889
2890// Similar to ExtensionMinimumVersionRequired test, but with different settings
2891// and orders.
2892IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequiredAlt) {
John Abd-El-Malek580bc96a52018-08-10 02:24:472893 ExtensionRequestInterceptor interceptor;
2894
2895 base::AtomicRefCount update_extension_count;
2896 interceptor.set_interceptor_hook(base::BindLambdaForTesting(
2897 [&](content::URLLoaderInterceptor::RequestParams* params) {
2898 if (params->url_request.url.host() == "update.extension" &&
2899 update_extension_count.IsZero()) {
2900 content::URLLoaderInterceptor::WriteResponse(
2901 "chrome/test/data/extensions/good2_update_manifest.xml",
2902 params->client.get());
2903 update_extension_count.Increment();
2904 return true;
2905 }
2906 return false;
2907 }));
2908
Devlin Cronin2824e9c2018-06-01 23:32:052909 extensions::ExtensionService* service = extension_service();
binjin8e3d0182014-12-04 16:44:282910 extensions::ExtensionRegistry* registry =
2911 extensions::ExtensionRegistry::Get(browser()->profile());
2912 extensions::ExtensionPrefs* extension_prefs =
2913 extensions::ExtensionPrefs::Get(browser()->profile());
2914
binjin8e3d0182014-12-04 16:44:282915 // Set the policy to require an even higher minimum version this time.
2916 {
2917 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2918 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.2");
2919 }
2920 base::RunLoop().RunUntilIdle();
2921
2922 // Install the 1.0.0.0 version, it should be installed but disabled.
2923 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
2924 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
Minh X. Nguyen45479012017-08-18 21:35:362925 EXPECT_EQ(extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY,
binjin8e3d0182014-12-04 16:44:282926 extension_prefs->GetDisableReasons(kGoodCrxId));
2927 EXPECT_EQ("1.0.0.0",
Devlin Cronin03bf2d22017-12-20 08:21:052928 service->GetInstalledExtension(kGoodCrxId)->version().GetString());
binjin8e3d0182014-12-04 16:44:282929
2930 // An extension management policy update should trigger an update as well.
John Abd-El-Malek580bc96a52018-08-10 02:24:472931 EXPECT_TRUE(update_extension_count.IsZero());
binjin8e3d0182014-12-04 16:44:282932 {
limasdf8fec6612015-10-12 10:03:062933 extensions::TestExtensionRegistryObserver update_observer(
2934 extensions::ExtensionRegistry::Get(browser()->profile()));
binjin8e3d0182014-12-04 16:44:282935 {
2936 // Set a higher minimum version, just intend to trigger a policy update.
2937 extensions::ExtensionManagementPolicyUpdater management_policy(
2938 &provider_);
2939 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.3");
2940 }
2941 base::RunLoop().RunUntilIdle();
limasdf8fec6612015-10-12 10:03:062942 update_observer.WaitForExtensionWillBeInstalled();
binjin8e3d0182014-12-04 16:44:282943 }
John Abd-El-Malek580bc96a52018-08-10 02:24:472944 EXPECT_TRUE(update_extension_count.IsOne());
binjin8e3d0182014-12-04 16:44:282945
2946 // It should be updated to 1.0.0.1 but remain disabled.
2947 EXPECT_EQ("1.0.0.1",
Devlin Cronin03bf2d22017-12-20 08:21:052948 service->GetInstalledExtension(kGoodCrxId)->version().GetString());
binjin8e3d0182014-12-04 16:44:282949 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
Minh X. Nguyen45479012017-08-18 21:35:362950 EXPECT_EQ(extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY,
binjin8e3d0182014-12-04 16:44:282951 extension_prefs->GetDisableReasons(kGoodCrxId));
2952
2953 // Remove the minimum version requirement. The extension should be re-enabled.
2954 {
2955 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2956 management_policy.UnsetMinimumVersionRequired(kGoodCrxId);
2957 }
2958 base::RunLoop().RunUntilIdle();
2959
2960 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2961 EXPECT_FALSE(extension_prefs->HasDisableReason(
Minh X. Nguyen45479012017-08-18 21:35:362962 kGoodCrxId,
2963 extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY));
binjin8e3d0182014-12-04 16:44:282964}
2965
2966// Verifies that a force-installed extension which does not meet a subsequently
2967// set minimum version requirement is handled well.
2968IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionForceInstalled) {
John Abd-El-Malek580bc96a52018-08-10 02:24:472969 ExtensionRequestInterceptor interceptor;
2970
Nick Petersond952cb772018-03-07 15:46:032971// Mark as enterprise managed.
2972#if defined(OS_WIN)
Roger Tawac1b544a82018-08-24 16:23:252973 base::win::ScopedDomainStateForTesting scoped_domain(true);
Nick Petersond952cb772018-03-07 15:46:032974#endif
binjin8e3d0182014-12-04 16:44:282975 extensions::ExtensionRegistry* registry =
2976 extensions::ExtensionRegistry::Get(browser()->profile());
2977 extensions::ExtensionPrefs* extension_prefs =
2978 extensions::ExtensionPrefs::Get(browser()->profile());
2979
2980 // Prepare the update URL for force installing.
John Abd-El-Malek580bc96a52018-08-10 02:24:472981 ASSERT_TRUE(embedded_test_server()->Start());
2982 GURL url =
2983 embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");
binjin8e3d0182014-12-04 16:44:282984
2985 // Set policy to force-install the extension, it should be installed and
2986 // enabled.
limasdf8fec6612015-10-12 10:03:062987 extensions::TestExtensionRegistryObserver install_observer(
2988 extensions::ExtensionRegistry::Get(browser()->profile()));
binjin8e3d0182014-12-04 16:44:282989 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2990 {
2991 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2992 management_policy.SetIndividualExtensionAutoInstalled(kGoodCrxId,
2993 url.spec(), true);
2994 }
2995 base::RunLoop().RunUntilIdle();
limasdf8fec6612015-10-12 10:03:062996 install_observer.WaitForExtensionWillBeInstalled();
binjin8e3d0182014-12-04 16:44:282997
2998 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2999
3000 // Set policy a minimum version of "1.0.0.1", the extension now should be
3001 // disabled.
3002 {
3003 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
3004 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
3005 }
3006 base::RunLoop().RunUntilIdle();
3007 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
3008 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
Minh X. Nguyen45479012017-08-18 21:35:363009 EXPECT_EQ(extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY,
binjin8e3d0182014-12-04 16:44:283010 extension_prefs->GetDisableReasons(kGoodCrxId));
3011}
3012
[email protected]ecde07ed2012-09-11 13:08:473013IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
3014 // Verifies that the homepage can be configured with policies.
3015 // Set a default, and check that the home button navigates there.
3016 browser()->profile()->GetPrefs()->SetString(
3017 prefs::kHomePage, chrome::kChromeUIPolicyURL);
3018 browser()->profile()->GetPrefs()->SetBoolean(
3019 prefs::kHomePageIsNewTabPage, false);
3020 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
3021 browser()->profile()->GetHomePage());
[email protected]617ee962013-01-29 20:49:123022 content::WebContents* contents =
3023 browser()->tab_strip_model()->GetActiveWebContents();
[email protected]8e09c7af2014-06-10 11:46:173024 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
[email protected]ecde07ed2012-09-11 13:08:473025 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
3026 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
3027
3028 // Now override with policy.
3029 PolicyMap policies;
ricea86fa1dd2016-09-13 05:59:453030 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
3031 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303032 std::make_unique<base::Value>(chrome::kChromeUICreditsURL),
ricea86fa1dd2016-09-13 05:59:453033 nullptr);
[email protected]161245d2013-01-09 14:28:113034 UpdateProviderPolicy(policies);
[email protected]ecde07ed2012-09-11 13:08:473035 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
3036 content::WaitForLoadStop(contents);
[email protected]a44a14f2012-09-26 22:48:223037 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
[email protected]ecde07ed2012-09-11 13:08:473038
dcheng3b344bc22016-05-10 02:26:093039 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
3040 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303041 std::make_unique<base::Value>(true), nullptr);
[email protected]161245d2013-01-09 14:28:113042 UpdateProviderPolicy(policies);
[email protected]ecde07ed2012-09-11 13:08:473043 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
[email protected]19506d542013-10-15 23:11:063044 content::WaitForLoadStop(contents);
Conley Owensaafcf122018-02-26 18:53:513045 EXPECT_TRUE(search::IsInstantNTP(contents));
[email protected]ecde07ed2012-09-11 13:08:473046}
3047
Guido Urdaneta3c8fefc02016-12-15 13:29:183048#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER)
3049// Flaky on ASAN on Mac. See https://crbug.com/674497.
3050#define MAYBE_IncognitoEnabled DISABLED_IncognitoEnabled
3051#else
3052#define MAYBE_IncognitoEnabled IncognitoEnabled
3053#endif
3054IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_IncognitoEnabled) {
[email protected]b8b27052012-08-29 14:05:163055 // Verifies that incognito windows can't be opened when disabled by policy.
3056
scottmg0d8e4ab2016-01-28 00:34:553057 const BrowserList* active_browser_list = BrowserList::GetInstance();
[email protected]0665ebe2013-02-13 09:53:193058
[email protected]b3fc7b72012-08-28 15:04:043059 // Disable incognito via policy and verify that incognito windows can't be
3060 // opened.
[email protected]7d1a810b2013-06-26 19:51:593061 EXPECT_EQ(1u, active_browser_list->size());
trizzofo49b95f52016-07-02 00:26:133062 EXPECT_FALSE(BrowserList::IsIncognitoSessionActive());
[email protected]b3fc7b72012-08-28 15:04:043063 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093064 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
3065 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303066 std::make_unique<base::Value>(false), nullptr);
[email protected]161245d2013-01-09 14:28:113067 UpdateProviderPolicy(policies);
[email protected]b3fc7b72012-08-28 15:04:043068 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
[email protected]7d1a810b2013-06-26 19:51:593069 EXPECT_EQ(1u, active_browser_list->size());
trizzofo49b95f52016-07-02 00:26:133070 EXPECT_FALSE(BrowserList::IsIncognitoSessionActive());
[email protected]b3fc7b72012-08-28 15:04:043071
3072 // Enable via policy and verify that incognito windows can be opened.
dcheng3b344bc22016-05-10 02:26:093073 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
3074 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303075 std::make_unique<base::Value>(true), nullptr);
[email protected]161245d2013-01-09 14:28:113076 UpdateProviderPolicy(policies);
[email protected]b3fc7b72012-08-28 15:04:043077 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
[email protected]7d1a810b2013-06-26 19:51:593078 EXPECT_EQ(2u, active_browser_list->size());
trizzofo49b95f52016-07-02 00:26:133079 EXPECT_TRUE(BrowserList::IsIncognitoSessionActive());
[email protected]b3fc7b72012-08-28 15:04:043080}
3081
[email protected]ea826362012-09-05 23:31:373082IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
3083 // Verifies that Javascript can be disabled.
[email protected]617ee962013-01-29 20:49:123084 content::WebContents* contents =
3085 browser()->tab_strip_model()->GetActiveWebContents();
[email protected]ea826362012-09-05 23:31:373086 EXPECT_TRUE(IsJavascriptEnabled(contents));
3087 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
3088 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
[email protected]2056c3192013-10-21 22:40:513089 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
[email protected]ea826362012-09-05 23:31:373090
3091 // Disable Javascript via policy.
3092 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093093 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
3094 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303095 std::make_unique<base::Value>(false), nullptr);
[email protected]161245d2013-01-09 14:28:113096 UpdateProviderPolicy(policies);
[email protected]ea826362012-09-05 23:31:373097 // Reload the page.
[email protected]8e09c7af2014-06-10 11:46:173098 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
[email protected]ea826362012-09-05 23:31:373099 EXPECT_FALSE(IsJavascriptEnabled(contents));
3100 // Developer tools still work when javascript is disabled.
3101 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
3102 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
[email protected]2056c3192013-10-21 22:40:513103 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
[email protected]ea826362012-09-05 23:31:373104 // Javascript is always enabled for the internal pages.
[email protected]e1f2b8aa2012-09-28 14:22:163105 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
[email protected]ea826362012-09-05 23:31:373106 EXPECT_TRUE(IsJavascriptEnabled(contents));
3107
3108 // The javascript content setting policy overrides the javascript policy.
[email protected]8e09c7af2014-06-10 11:46:173109 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
[email protected]ea826362012-09-05 23:31:373110 EXPECT_FALSE(IsJavascriptEnabled(contents));
ricea86fa1dd2016-09-13 05:59:453111 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
3112 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303113 std::make_unique<base::Value>(CONTENT_SETTING_ALLOW), nullptr);
[email protected]161245d2013-01-09 14:28:113114 UpdateProviderPolicy(policies);
[email protected]8e09c7af2014-06-10 11:46:173115 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
[email protected]ea826362012-09-05 23:31:373116 EXPECT_TRUE(IsJavascriptEnabled(contents));
3117}
3118
[email protected]27ef988d2014-08-01 17:00:403119IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
3120 PrefService* prefs = browser()->profile()->GetPrefs();
3121
3122 // Enabled by default.
3123 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
3124
3125 // Disable by old, deprecated policy.
3126 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093127 policies.Set(key::kDnsPrefetchingEnabled, POLICY_LEVEL_MANDATORY,
3128 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303129 std::make_unique<base::Value>(false), nullptr);
[email protected]27ef988d2014-08-01 17:00:403130 UpdateProviderPolicy(policies);
3131
3132 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
3133
3134 // Enabled by new policy, this should override old one.
dcheng3b344bc22016-05-10 02:26:093135 policies.Set(key::kNetworkPredictionOptions, POLICY_LEVEL_MANDATORY,
3136 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303137 std::make_unique<base::Value>(
ricea86fa1dd2016-09-13 05:59:453138 chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
dcheng3b344bc22016-05-10 02:26:093139 nullptr);
[email protected]27ef988d2014-08-01 17:00:403140 UpdateProviderPolicy(policies);
3141
3142 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
3143}
3144
[email protected]b8b27052012-08-29 14:05:163145IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
3146 // Verifies that browsing history is not saved.
3147 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093148 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
3149 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303150 std::make_unique<base::Value>(true), nullptr);
[email protected]161245d2013-01-09 14:28:113151 UpdateProviderPolicy(policies);
[email protected]b8b27052012-08-29 14:05:163152 GURL url = ui_test_utils::GetTestUrl(
[email protected]650b2d52013-02-10 03:41:453153 base::FilePath(base::FilePath::kCurrentDirectory),
3154 base::FilePath(FILE_PATH_LITERAL("empty.html")));
[email protected]b8b27052012-08-29 14:05:163155 ui_test_utils::NavigateToURL(browser(), url);
3156 // Verify that the navigation wasn't saved in the history.
[email protected]2fa639482012-08-30 19:32:043157 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
[email protected]b8b27052012-08-29 14:05:163158 EXPECT_EQ(0u, enumerator1.urls().size());
3159
3160 // Now flip the policy and try again.
dcheng3b344bc22016-05-10 02:26:093161 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
3162 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303163 std::make_unique<base::Value>(false), nullptr);
[email protected]161245d2013-01-09 14:28:113164 UpdateProviderPolicy(policies);
[email protected]b8b27052012-08-29 14:05:163165 ui_test_utils::NavigateToURL(browser(), url);
3166 // Verify that the navigation was saved in the history.
[email protected]2fa639482012-08-30 19:32:043167 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
[email protected]b8b27052012-08-29 14:05:163168 ASSERT_EQ(1u, enumerator2.urls().size());
3169 EXPECT_EQ(url, enumerator2.urls()[0]);
3170}
3171
dullweber303f4442017-03-03 11:50:193172IN_PROC_BROWSER_TEST_F(PolicyTest, DeletingBrowsingHistoryDisabled) {
3173 // Verifies that deleting the browsing history can be disabled.
3174
3175 PrefService* prefs = browser()->profile()->GetPrefs();
3176 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kAllowDeletingBrowserHistory));
3177 EXPECT_TRUE(prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory));
3178
3179 EXPECT_TRUE(prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory));
3180 EXPECT_TRUE(prefs->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory));
3181 EXPECT_TRUE(
3182 prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistoryBasic));
3183
3184 PolicyMap policies;
3185 policies.Set(key::kAllowDeletingBrowserHistory, POLICY_LEVEL_MANDATORY,
3186 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303187 std::make_unique<base::Value>(true), nullptr);
dullweber303f4442017-03-03 11:50:193188 UpdateProviderPolicy(policies);
3189 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kAllowDeletingBrowserHistory));
3190 EXPECT_TRUE(prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory));
3191
3192 EXPECT_TRUE(prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory));
3193 EXPECT_TRUE(prefs->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory));
3194 EXPECT_TRUE(
3195 prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistoryBasic));
3196
3197 policies.Set(key::kAllowDeletingBrowserHistory, POLICY_LEVEL_MANDATORY,
3198 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303199 std::make_unique<base::Value>(false), nullptr);
dullweber303f4442017-03-03 11:50:193200 UpdateProviderPolicy(policies);
3201 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kAllowDeletingBrowserHistory));
3202 EXPECT_FALSE(prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory));
3203
3204 EXPECT_FALSE(prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory));
3205 EXPECT_FALSE(prefs->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory));
3206 EXPECT_FALSE(
3207 prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistoryBasic));
3208
3209 policies.Clear();
3210 UpdateProviderPolicy(policies);
3211 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kAllowDeletingBrowserHistory));
3212 EXPECT_TRUE(prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory));
3213
3214 EXPECT_TRUE(prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistory));
3215 EXPECT_TRUE(prefs->GetBoolean(browsing_data::prefs::kDeleteDownloadHistory));
3216 EXPECT_TRUE(
3217 prefs->GetBoolean(browsing_data::prefs::kDeleteBrowsingHistoryBasic));
3218}
3219
hansf281a582015-11-02 23:23:183220// TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
3221#if !defined(USE_AURA)
[email protected]884e4d7a2013-05-17 05:48:243222// http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
3223IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
[email protected]b8b27052012-08-29 14:05:163224 // Verifies that translate can be forced enabled or disabled by policy.
3225
[email protected]4f822f022012-12-20 19:11:423226 // Get the InfoBarService, and verify that there are no infobars on startup.
[email protected]617ee962013-01-29 20:49:123227 content::WebContents* contents =
3228 browser()->tab_strip_model()->GetActiveWebContents();
[email protected]850b4be2012-08-28 15:10:343229 ASSERT_TRUE(contents);
[email protected]4f822f022012-12-20 19:11:423230 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
3231 ASSERT_TRUE(infobar_service);
[email protected]b44f1d32014-04-10 13:53:263232 EXPECT_EQ(0u, infobar_service->infobar_count());
[email protected]850b4be2012-08-28 15:10:343233
3234 // Force enable the translate feature.
3235 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093236 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
3237 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:193238 base::WrapUnique(new base::Value(true)), nullptr);
[email protected]161245d2013-01-09 14:28:113239 UpdateProviderPolicy(policies);
Avi Drissmand3f956d72018-04-02 21:44:073240 // Instead of waiting for an infobar, this test waits for
3241 // NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
[email protected]850b4be2012-08-28 15:10:343242 // TranslateManager observes. This allows checking that an infobar is NOT
Avi Drissmand3f956d72018-04-02 21:44:073243 // shown below, without polling for infobars for some indeterminate amount of
3244 // time.
[email protected]850b4be2012-08-28 15:10:343245 GURL url = ui_test_utils::GetTestUrl(
[email protected]c727beda92013-05-03 13:50:323246 base::FilePath(),
3247 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
[email protected]850b4be2012-08-28 15:10:343248 content::WindowedNotificationObserver language_observer1(
3249 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
3250 content::NotificationService::AllSources());
3251 ui_test_utils::NavigateToURL(browser(), url);
3252 language_observer1.Wait();
[email protected]c727beda92013-05-03 13:50:323253
3254 // Verify the translation detected for this tab.
[email protected]255ab972014-06-04 12:14:223255 ChromeTranslateClient* chrome_translate_client =
3256 ChromeTranslateClient::FromWebContents(contents);
3257 ASSERT_TRUE(chrome_translate_client);
[email protected]e5e72cc2014-07-22 19:06:493258 translate::LanguageState& language_state =
3259 chrome_translate_client->GetLanguageState();
[email protected]c727beda92013-05-03 13:50:323260 EXPECT_EQ("fr", language_state.original_language());
[email protected]54e4b522013-05-21 08:36:233261 EXPECT_TRUE(language_state.page_needs_translation());
[email protected]c727beda92013-05-03 13:50:323262 EXPECT_FALSE(language_state.translation_pending());
3263 EXPECT_FALSE(language_state.translation_declined());
3264 EXPECT_FALSE(language_state.IsPageTranslated());
3265
[email protected]850b4be2012-08-28 15:10:343266 // Verify that the translate infobar showed up.
[email protected]b44f1d32014-04-10 13:53:263267 ASSERT_EQ(1u, infobar_service->infobar_count());
[email protected]051655ad2014-04-18 15:09:413268 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
[email protected]e5e72cc2014-07-22 19:06:493269 translate::TranslateInfoBarDelegate* translate_infobar_delegate =
[email protected]39308cb2013-12-06 03:01:483270 infobar->delegate()->AsTranslateInfoBarDelegate();
[email protected]4ee3c912013-07-19 20:20:423271 ASSERT_TRUE(translate_infobar_delegate);
[email protected]b5d22782014-04-07 11:02:093272 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
[email protected]bccf5ab2014-02-15 08:20:303273 translate_infobar_delegate->translate_step());
[email protected]4ee3c912013-07-19 20:20:423274 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
[email protected]850b4be2012-08-28 15:10:343275
3276 // Now force disable translate.
[email protected]b44f1d32014-04-10 13:53:263277 infobar_service->RemoveInfoBar(infobar);
3278 EXPECT_EQ(0u, infobar_service->infobar_count());
dcheng3b344bc22016-05-10 02:26:093279 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
3280 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:193281 base::WrapUnique(new base::Value(false)), nullptr);
[email protected]161245d2013-01-09 14:28:113282 UpdateProviderPolicy(policies);
[email protected]850b4be2012-08-28 15:10:343283 // Navigating to the same URL now doesn't trigger an infobar.
3284 content::WindowedNotificationObserver language_observer2(
3285 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
3286 content::NotificationService::AllSources());
3287 ui_test_utils::NavigateToURL(browser(), url);
3288 language_observer2.Wait();
[email protected]b44f1d32014-04-10 13:53:263289 EXPECT_EQ(0u, infobar_service->infobar_count());
[email protected]850b4be2012-08-28 15:10:343290}
hansf281a582015-11-02 23:23:183291#endif // !defined(USE_AURA)
[email protected]850b4be2012-08-28 15:10:343292
[email protected]307aec72012-09-18 21:52:443293IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
[email protected]38a4db92012-08-29 09:36:053294 // Checks that URLs can be blacklisted, and that exceptions can be made to
3295 // the blacklist.
[email protected]233b688e2012-11-27 10:44:123296
Yuzhu Shen6ccfd562017-10-27 16:38:183297 ASSERT_TRUE(embedded_test_server()->Start());
3298
3299 const std::string kURLS[] = {
3300 embedded_test_server()->GetURL("aaa.com", "/empty.html").spec(),
3301 embedded_test_server()->GetURL("bbb.com", "/empty.html").spec(),
3302 embedded_test_server()->GetURL("sub.bbb.com", "/empty.html").spec(),
3303 embedded_test_server()->GetURL("bbb.com", "/policy/blank.html").spec(),
3304 embedded_test_server()->GetURL("bbb.com.", "/policy/blank.html").spec(),
[email protected]38a4db92012-08-29 09:36:053305 };
[email protected]38a4db92012-08-29 09:36:053306
[email protected]00367e02013-03-19 20:07:563307 // Verify that "bbb.com" opens before applying the blacklist.
jamd6be16e2014-09-28 15:18:343308 CheckCanOpenURL(browser(), kURLS[1]);
[email protected]38a4db92012-08-29 09:36:053309
3310 // Set a blacklist.
3311 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:183312 blacklist.AppendString("bbb.com");
[email protected]38a4db92012-08-29 09:36:053313 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093314 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3315 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
[email protected]161245d2013-01-09 14:28:113316 UpdateProviderPolicy(policies);
[email protected]307aec72012-09-18 21:52:443317 FlushBlacklistPolicy();
[email protected]00367e02013-03-19 20:07:563318 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
jamd6be16e2014-09-28 15:18:343319 CheckCanOpenURL(browser(), kURLS[0]);
Avi Drissman5f0fb8c2018-12-25 23:20:493320 for (size_t i = 1; i < base::size(kURLS); ++i)
jamd6be16e2014-09-28 15:18:343321 CheckURLIsBlocked(browser(), kURLS[i]);
[email protected]38a4db92012-08-29 09:36:053322
3323 // Whitelist some sites of bbb.com.
3324 base::ListValue whitelist;
dchengd9ea63862016-06-03 02:27:183325 whitelist.AppendString("sub.bbb.com");
3326 whitelist.AppendString("bbb.com/policy");
dcheng3b344bc22016-05-10 02:26:093327 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3328 POLICY_SOURCE_CLOUD, whitelist.CreateDeepCopy(), nullptr);
[email protected]161245d2013-01-09 14:28:113329 UpdateProviderPolicy(policies);
[email protected]307aec72012-09-18 21:52:443330 FlushBlacklistPolicy();
jamd6be16e2014-09-28 15:18:343331 CheckURLIsBlocked(browser(), kURLS[1]);
3332 CheckCanOpenURL(browser(), kURLS[2]);
3333 CheckCanOpenURL(browser(), kURLS[3]);
mnisslerd9cdcd872015-05-29 13:57:413334 CheckCanOpenURL(browser(), kURLS[4]);
[email protected]38a4db92012-08-29 09:36:053335}
3336
Doug Turnerb4927e72018-03-14 17:03:443337IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklistIncognito) {
3338 // Checks that URLs can be blacklisted, and that exceptions can be made to
3339 // the blacklist.
3340
3341 Browser* incognito_browser =
3342 OpenURLOffTheRecord(browser()->profile(), GURL("about:blank"));
3343
3344 ASSERT_TRUE(embedded_test_server()->Start());
3345
3346 const std::string kURLS[] = {
3347 embedded_test_server()->GetURL("aaa.com", "/empty.html").spec(),
3348 embedded_test_server()->GetURL("bbb.com", "/empty.html").spec(),
3349 embedded_test_server()->GetURL("sub.bbb.com", "/empty.html").spec(),
3350 embedded_test_server()->GetURL("bbb.com", "/policy/blank.html").spec(),
3351 embedded_test_server()->GetURL("bbb.com.", "/policy/blank.html").spec(),
3352 };
3353
3354 // Verify that "bbb.com" opens before applying the blacklist.
3355 CheckCanOpenURL(incognito_browser, kURLS[1]);
3356
3357 // Set a blacklist.
3358 base::ListValue blacklist;
3359 blacklist.AppendString("bbb.com");
3360 PolicyMap policies;
3361 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3362 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
3363 UpdateProviderPolicy(policies);
3364 FlushBlacklistPolicy();
3365 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
3366 CheckCanOpenURL(incognito_browser, kURLS[0]);
Avi Drissman5f0fb8c2018-12-25 23:20:493367 for (size_t i = 1; i < base::size(kURLS); ++i)
Doug Turnerb4927e72018-03-14 17:03:443368 CheckURLIsBlocked(incognito_browser, kURLS[i]);
3369
3370 // Whitelist some sites of bbb.com.
3371 base::ListValue whitelist;
3372 whitelist.AppendString("sub.bbb.com");
3373 whitelist.AppendString("bbb.com/policy");
3374 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3375 POLICY_SOURCE_CLOUD, whitelist.CreateDeepCopy(), nullptr);
3376 UpdateProviderPolicy(policies);
3377 FlushBlacklistPolicy();
3378 CheckURLIsBlocked(incognito_browser, kURLS[1]);
3379 CheckCanOpenURL(incognito_browser, kURLS[2]);
3380 CheckCanOpenURL(incognito_browser, kURLS[3]);
3381 CheckCanOpenURL(incognito_browser, kURLS[4]);
3382}
3383
John Abd-El-Malek337a87dc2017-08-16 15:06:023384IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklistAndWhitelist) {
3385 // Regression test for http://crbug.com/755256. Blacklisting * and
3386 // whitelisting an origin should work.
3387
Yuzhu Shen6ccfd562017-10-27 16:38:183388 ASSERT_TRUE(embedded_test_server()->Start());
John Abd-El-Malek337a87dc2017-08-16 15:06:023389
3390 base::ListValue blacklist;
3391 blacklist.AppendString("*");
3392 PolicyMap policies;
3393 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3394 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
3395
3396 base::ListValue whitelist;
3397 whitelist.AppendString("aaa.com");
3398 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3399 POLICY_SOURCE_CLOUD, whitelist.CreateDeepCopy(), nullptr);
3400 UpdateProviderPolicy(policies);
3401 FlushBlacklistPolicy();
Yuzhu Shen6ccfd562017-10-27 16:38:183402 CheckCanOpenURL(
3403 browser(),
3404 embedded_test_server()->GetURL("aaa.com", "/empty.html").spec());
John Abd-El-Malek337a87dc2017-08-16 15:06:023405}
3406
mmenkefb2ba512015-06-04 14:00:373407IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklistSubresources) {
3408 // Checks that an image with a blacklisted URL is loaded, but an iframe with a
3409 // blacklisted URL is not.
3410
Yuzhu Shen6ccfd562017-10-27 16:38:183411 ASSERT_TRUE(embedded_test_server()->Start());
3412
tfarina5e7b57232015-10-17 23:37:403413 GURL main_url =
Yuzhu Shen6ccfd562017-10-27 16:38:183414 embedded_test_server()->GetURL("/policy/blacklist-subresources.html");
3415 GURL image_url = embedded_test_server()->GetURL("/policy/pixel.png");
3416 GURL subframe_url = embedded_test_server()->GetURL("/policy/blank.html");
mmenkefb2ba512015-06-04 14:00:373417
3418 // Set a blacklist containing the image and the iframe which are used by the
3419 // main document.
3420 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:183421 blacklist.AppendString(image_url.spec().c_str());
3422 blacklist.AppendString(subframe_url.spec().c_str());
mmenkefb2ba512015-06-04 14:00:373423 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093424 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3425 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
mmenkefb2ba512015-06-04 14:00:373426 UpdateProviderPolicy(policies);
3427 FlushBlacklistPolicy();
3428
3429 std::string blacklisted_image_load_result;
3430 ui_test_utils::NavigateToURL(browser(), main_url);
3431 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3432 browser()->tab_strip_model()->GetActiveWebContents(),
3433 "window.domAutomationController.send(imageLoadResult)",
3434 &blacklisted_image_load_result));
3435 EXPECT_EQ("success", blacklisted_image_load_result);
3436
3437 std::string blacklisted_iframe_load_result;
3438 ui_test_utils::NavigateToURL(browser(), main_url);
3439 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3440 browser()->tab_strip_model()->GetActiveWebContents(),
3441 "window.domAutomationController.send(iframeLoadResult)",
3442 &blacklisted_iframe_load_result));
3443 EXPECT_EQ("error", blacklisted_iframe_load_result);
3444}
3445
Doug Turnerbbcf5e22017-12-21 22:43:073446IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklistClientRedirect) {
3447 // Checks that a client side redirect to a blacklisted URL is blocked.
3448 ASSERT_TRUE(embedded_test_server()->Start());
3449
3450 GURL redirected_url =
3451 embedded_test_server()->GetURL("/policy/blacklist-redirect.html");
3452 GURL first_url = embedded_test_server()->GetURL("/client-redirect?" +
3453 redirected_url.spec());
3454
Doug Turner43b5c502018-02-06 16:30:493455 // There are two navigations: one when loading client-redirect.html and
3456 // another when the document redirects using http-equiv="refresh".
3457 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
3458 first_url, 2);
Doug Turnerbbcf5e22017-12-21 22:43:073459 EXPECT_EQ(base::ASCIIToUTF16("Redirected!"),
3460 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
3461
3462 base::ListValue blacklist;
3463 blacklist.AppendString(redirected_url.spec().c_str());
3464 PolicyMap policies;
3465 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3466 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
3467 UpdateProviderPolicy(policies);
3468 FlushBlacklistPolicy();
3469
3470 ui_test_utils::NavigateToURL(browser(), first_url);
3471 content::WaitForLoadStop(
3472 browser()->tab_strip_model()->GetActiveWebContents());
3473 EXPECT_NE(base::ASCIIToUTF16("Redirected!"),
3474 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
3475}
3476
3477IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklistServerRedirect) {
3478 // Checks that a server side redirect to a blacklisted URL is blocked.
3479 ASSERT_TRUE(embedded_test_server()->Start());
3480
3481 GURL redirected_url =
3482 embedded_test_server()->GetURL("/policy/blacklist-redirect.html");
3483 GURL first_url = embedded_test_server()->GetURL("/server-redirect?" +
3484 redirected_url.spec());
3485
3486 ui_test_utils::NavigateToURL(browser(), first_url);
3487 content::WaitForLoadStop(
3488 browser()->tab_strip_model()->GetActiveWebContents());
3489 EXPECT_EQ(base::ASCIIToUTF16("Redirected!"),
3490 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
3491
3492 base::ListValue blacklist;
3493 blacklist.AppendString(redirected_url.spec().c_str());
3494 PolicyMap policies;
3495 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3496 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
3497 UpdateProviderPolicy(policies);
3498 FlushBlacklistPolicy();
3499
3500 ui_test_utils::NavigateToURL(browser(), first_url);
3501 content::WaitForLoadStop(
3502 browser()->tab_strip_model()->GetActiveWebContents());
3503 EXPECT_NE(base::ASCIIToUTF16("Redirected!"),
3504 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
3505}
3506
jamd6be16e2014-09-28 15:18:343507#if defined(OS_MACOSX)
3508// http://crbug.com/339240
3509#define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
3510#else
3511#define MAYBE_FileURLBlacklist FileURLBlacklist
3512#endif
3513IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
[email protected]8f810632013-06-06 22:33:323514 // Check that FileURLs can be blacklisted and DisabledSchemes works together
3515 // with URLblacklisting and URLwhitelisting.
3516
3517 base::FilePath test_path;
Jun Caiaa248692017-11-10 20:10:513518 GetTestDataDirectory(&test_path);
[email protected]8f810632013-06-06 22:33:323519 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
3520 const std::string folder_path = base_path + "apptest/";
3521 const std::string file_path1 = base_path + "title1.html";
3522 const std::string file_path2 = folder_path + "basic.html";
3523
Yuzhu Shen6ccfd562017-10-27 16:38:183524 CheckCanOpenURL(browser(), file_path1);
3525 CheckCanOpenURL(browser(), file_path2);
[email protected]8f810632013-06-06 22:33:323526
3527 // Set a blacklist for all the files.
3528 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:183529 blacklist.AppendString("file://*");
[email protected]8f810632013-06-06 22:33:323530 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093531 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3532 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
[email protected]8f810632013-06-06 22:33:323533 UpdateProviderPolicy(policies);
3534 FlushBlacklistPolicy();
3535
Yuzhu Shen6ccfd562017-10-27 16:38:183536 CheckURLIsBlocked(browser(), file_path1);
3537 CheckURLIsBlocked(browser(), file_path2);
[email protected]8f810632013-06-06 22:33:323538
3539 // Replace the URLblacklist with disabling the file scheme.
jdoerrie122c4da2017-03-06 11:12:043540 blacklist.Remove(base::Value("file://*"), NULL);
dcheng3b344bc22016-05-10 02:26:093541 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3542 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
[email protected]8f810632013-06-06 22:33:323543 UpdateProviderPolicy(policies);
3544 FlushBlacklistPolicy();
3545
3546 PrefService* prefs = browser()->profile()->GetPrefs();
[email protected]425e3372013-12-17 09:35:433547 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
jdoerrie122c4da2017-03-06 11:12:043548 EXPECT_EQ(list_url->Find(base::Value("file://*")), list_url->end());
[email protected]8f810632013-06-06 22:33:323549
3550 base::ListValue disabledscheme;
dchengd9ea63862016-06-03 02:27:183551 disabledscheme.AppendString("file");
dcheng3b344bc22016-05-10 02:26:093552 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3553 POLICY_SOURCE_CLOUD, disabledscheme.CreateDeepCopy(), nullptr);
[email protected]8f810632013-06-06 22:33:323554 UpdateProviderPolicy(policies);
3555 FlushBlacklistPolicy();
3556
[email protected]425e3372013-12-17 09:35:433557 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
jdoerrie122c4da2017-03-06 11:12:043558 EXPECT_NE(list_url->Find(base::Value("file://*")), list_url->end());
[email protected]8f810632013-06-06 22:33:323559
3560 // Whitelist one folder and blacklist an another just inside.
3561 base::ListValue whitelist;
dchengd9ea63862016-06-03 02:27:183562 whitelist.AppendString(base_path);
dcheng3b344bc22016-05-10 02:26:093563 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3564 POLICY_SOURCE_CLOUD, whitelist.CreateDeepCopy(), nullptr);
dchengd9ea63862016-06-03 02:27:183565 blacklist.AppendString(folder_path);
dcheng3b344bc22016-05-10 02:26:093566 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3567 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
[email protected]8f810632013-06-06 22:33:323568 UpdateProviderPolicy(policies);
3569 FlushBlacklistPolicy();
3570
Yuzhu Shen6ccfd562017-10-27 16:38:183571 CheckCanOpenURL(browser(), file_path1);
3572 CheckURLIsBlocked(browser(), file_path2);
[email protected]8f810632013-06-06 22:33:323573}
3574
Thomas Tangl6703fceb2018-07-18 15:54:253575IN_PROC_BROWSER_TEST_F(PolicyTest, UrlKeyedAnonymizedDataCollection) {
3576 PrefService* prefs = browser()->profile()->GetPrefs();
3577 prefs->SetBoolean(
3578 unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled, true);
3579 EXPECT_TRUE(prefs->GetBoolean(
3580 unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled));
3581
3582 // Disable by policy.
3583 PolicyMap policies;
3584 policies.Set(key::kUrlKeyedAnonymizedDataCollectionEnabled,
3585 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
3586 std::make_unique<base::Value>(false), nullptr);
3587 UpdateProviderPolicy(policies);
3588
3589 EXPECT_FALSE(prefs->GetBoolean(
3590 unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled));
3591}
3592
[email protected]32dfede2013-08-25 15:48:253593#if !defined(OS_MACOSX)
[email protected]369d5a52013-09-18 10:09:533594IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
[email protected]32dfede2013-08-25 15:48:253595 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093596 policies.Set(key::kFullscreenAllowed, POLICY_LEVEL_MANDATORY,
3597 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303598 std::make_unique<base::Value>(false), nullptr);
[email protected]32dfede2013-08-25 15:48:253599 UpdateProviderPolicy(policies);
3600
3601 BrowserWindow* browser_window = browser()->window();
3602 ASSERT_TRUE(browser_window);
3603
3604 EXPECT_FALSE(browser_window->IsFullscreen());
3605 chrome::ToggleFullscreenMode(browser());
3606 EXPECT_FALSE(browser_window->IsFullscreen());
3607}
[email protected]369d5a52013-09-18 10:09:533608
3609IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
3610 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093611 policies.Set(key::kFullscreenAllowed, POLICY_LEVEL_MANDATORY,
3612 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303613 std::make_unique<base::Value>(false), nullptr);
[email protected]369d5a52013-09-18 10:09:533614 UpdateProviderPolicy(policies);
3615
limasdfc83e0b72017-03-03 17:08:353616 scoped_refptr<const extensions::Extension> extension =
3617 LoadUnpackedExtension(kUnpackedFullscreenAppName);
[email protected]369d5a52013-09-18 10:09:533618 ASSERT_TRUE(extension);
3619
3620 // Launch an app that tries to open a fullscreen window.
[email protected]dbb03fb2014-02-15 05:36:333621 TestAddAppWindowObserver add_window_observer(
hashimotoad3c6872014-08-29 09:46:573622 extensions::AppWindowRegistry::Get(browser()->profile()));
Eric Willigers618e1302019-06-23 23:03:473623 OpenApplication(
3624 AppLaunchParams(browser()->profile(), extension->id(),
3625 extensions::LaunchContainer::kLaunchContainerNone,
3626 WindowOpenDisposition::NEW_WINDOW,
3627 extensions::AppLaunchSource::kSourceTest));
hashimotoad3c6872014-08-29 09:46:573628 extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
[email protected]369d5a52013-09-18 10:09:533629 ASSERT_TRUE(window);
3630
3631 // Verify that the window is not in fullscreen mode.
3632 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
3633
jam2637dd12016-09-23 16:39:183634 // For PlzNavigate case, we have to wait for the navigation to commit since
3635 // the JS object registration is delayed (see
3636 // AppWindowCreateFunction::RunAsync).
3637 content::WaitForLoadStop(window->web_contents());
3638
[email protected]369d5a52013-09-18 10:09:533639 // Verify that the window cannot be toggled into fullscreen mode via apps
3640 // APIs.
3641 EXPECT_TRUE(content::ExecuteScript(
3642 window->web_contents(),
3643 "chrome.app.window.current().fullscreen();"));
3644 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
3645
3646 // Verify that the window cannot be toggled into fullscreen mode from within
3647 // Chrome (e.g., using keyboard accelerators).
3648 window->Fullscreen();
3649 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
3650}
[email protected]32dfede2013-08-25 15:48:253651#endif
3652
[email protected]7ea48702012-09-03 20:41:063653#if defined(OS_CHROMEOS)
earthdok9f1ec6f2015-04-14 19:55:433654
kjellanderd2c07742016-09-12 07:59:573655// Flaky on MSan (crbug.com/476964) and regular Chrome OS (crbug.com/645769).
3656IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_DisableScreenshotsFile) {
[email protected]7ea48702012-09-03 20:41:063657 int screenshot_count = CountScreenshots();
3658
3659 // Make sure screenshots are counted correctly.
3660 TestScreenshotFile(true);
3661 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
3662
3663 // Check if trying to take a screenshot fails when disabled by policy.
3664 TestScreenshotFile(false);
3665 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
3666}
[email protected]6af5e302012-09-20 19:29:093667
[email protected]934e3c92013-08-01 00:18:233668IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
[email protected]6af5e302012-09-20 19:29:093669 // Set up the mock observer.
[email protected]934e3c92013-08-01 00:18:233670 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
dcheng08cfe9ba2016-04-14 17:46:453671 std::unique_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
[email protected]934e3c92013-08-01 00:18:233672 audio_handler->AddAudioObserver(test_observer.get());
[email protected]6af5e302012-09-20 19:29:093673
[email protected]934e3c92013-08-01 00:18:233674 bool prior_state = audio_handler->IsOutputMuted();
3675 // Make sure the audio is not muted and then toggle the policy and observe
3676 // if the output mute changed event is fired.
3677 audio_handler->SetOutputMute(false);
3678 EXPECT_FALSE(audio_handler->IsOutputMuted());
3679 EXPECT_EQ(1, test_observer->output_mute_changed_count());
[email protected]6af5e302012-09-20 19:29:093680 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093681 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
3682 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303683 std::make_unique<base::Value>(false), nullptr);
[email protected]161245d2013-01-09 14:28:113684 UpdateProviderPolicy(policies);
[email protected]934e3c92013-08-01 00:18:233685 EXPECT_TRUE(audio_handler->IsOutputMuted());
3686 // This should not change the state now and should not trigger output mute
3687 // changed event.
3688 audio_handler->SetOutputMute(false);
3689 EXPECT_TRUE(audio_handler->IsOutputMuted());
3690 EXPECT_EQ(1, test_observer->output_mute_changed_count());
[email protected]6af5e302012-09-20 19:29:093691
[email protected]934e3c92013-08-01 00:18:233692 // Toggle back and observe if the output mute changed event is fired.
dcheng3b344bc22016-05-10 02:26:093693 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
3694 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303695 std::make_unique<base::Value>(true), nullptr);
[email protected]161245d2013-01-09 14:28:113696 UpdateProviderPolicy(policies);
[email protected]934e3c92013-08-01 00:18:233697 EXPECT_FALSE(audio_handler->IsOutputMuted());
3698 EXPECT_EQ(1, test_observer->output_mute_changed_count());
3699 audio_handler->SetOutputMute(true);
3700 EXPECT_TRUE(audio_handler->IsOutputMuted());
3701 EXPECT_EQ(2, test_observer->output_mute_changed_count());
[email protected]6af5e302012-09-20 19:29:093702 // Revert the prior state.
[email protected]934e3c92013-08-01 00:18:233703 audio_handler->SetOutputMute(prior_state);
3704 audio_handler->RemoveAudioObserver(test_observer.get());
[email protected]6af5e302012-09-20 19:29:093705}
[email protected]9a8764b2013-03-27 16:18:093706
achuithaf1ca272015-10-29 22:53:213707IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_SessionLengthLimit) {
[email protected]8e0ba06b2013-10-28 15:38:093708 // Indicate that the session started 2 hours ago and no user activity has
3709 // occurred yet.
[email protected]9a8764b2013-03-27 16:18:093710 g_browser_process->local_state()->SetInt64(
3711 prefs::kSessionStartTime,
3712 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
3713 .ToInternalValue());
3714}
3715
achuithaf1ca272015-10-29 22:53:213716IN_PROC_BROWSER_TEST_F(PolicyTest, SessionLengthLimit) {
[email protected]9a8764b2013-03-27 16:18:093717 content::MockNotificationObserver observer;
3718 content::NotificationRegistrar registrar;
3719 registrar.Add(&observer,
3720 chrome::NOTIFICATION_APP_TERMINATING,
3721 content::NotificationService::AllSources());
3722
3723 // Set the session length limit to 3 hours. Verify that the session is not
3724 // terminated.
3725 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
3726 .Times(0);
3727 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093728 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
3729 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303730 std::make_unique<base::Value>(kThreeHoursInMs), nullptr);
[email protected]9a8764b2013-03-27 16:18:093731 UpdateProviderPolicy(policies);
3732 base::RunLoop().RunUntilIdle();
3733 Mock::VerifyAndClearExpectations(&observer);
3734
3735 // Decrease the session length limit to 1 hour. Verify that the session is
3736 // terminated immediately.
3737 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
dcheng3b344bc22016-05-10 02:26:093738 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
3739 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303740 std::make_unique<base::Value>(kOneHourInMs), nullptr);
[email protected]8e0ba06b2013-10-28 15:38:093741 UpdateProviderPolicy(policies);
3742 base::RunLoop().RunUntilIdle();
3743 Mock::VerifyAndClearExpectations(&observer);
3744}
3745
achuith171b0612015-11-17 18:44:523746// Disabled, see http://crbug.com/554728.
[email protected]69c0c6862013-11-05 23:30:233747IN_PROC_BROWSER_TEST_F(PolicyTest,
achuith171b0612015-11-17 18:44:523748 DISABLED_PRE_WaitForInitialUserActivityUnsatisfied) {
[email protected]8e0ba06b2013-10-28 15:38:093749 // Indicate that the session started 2 hours ago and no user activity has
3750 // occurred yet.
3751 g_browser_process->local_state()->SetInt64(
3752 prefs::kSessionStartTime,
3753 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
3754 .ToInternalValue());
3755}
3756
achuith171b0612015-11-17 18:44:523757// Disabled, see http://crbug.com/554728.
[email protected]69c0c6862013-11-05 23:30:233758IN_PROC_BROWSER_TEST_F(PolicyTest,
achuith171b0612015-11-17 18:44:523759 DISABLED_WaitForInitialUserActivityUnsatisfied) {
[email protected]8e0ba06b2013-10-28 15:38:093760 content::MockNotificationObserver observer;
3761 content::NotificationRegistrar registrar;
3762 registrar.Add(&observer,
3763 chrome::NOTIFICATION_APP_TERMINATING,
3764 content::NotificationService::AllSources());
3765
3766 // Require initial user activity.
3767 PolicyMap policies;
3768 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:093769 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:193770 base::WrapUnique(new base::Value(true)), nullptr);
[email protected]8e0ba06b2013-10-28 15:38:093771 UpdateProviderPolicy(policies);
3772 base::RunLoop().RunUntilIdle();
3773
3774 // Set the session length limit to 1 hour. Verify that the session is not
3775 // terminated.
3776 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
3777 .Times(0);
dcheng3b344bc22016-05-10 02:26:093778 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
3779 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:193780 base::WrapUnique(new base::Value(kOneHourInMs)), nullptr);
[email protected]8e0ba06b2013-10-28 15:38:093781 UpdateProviderPolicy(policies);
3782 base::RunLoop().RunUntilIdle();
3783 Mock::VerifyAndClearExpectations(&observer);
3784}
3785
[email protected]69c0c6862013-11-05 23:30:233786IN_PROC_BROWSER_TEST_F(PolicyTest,
achuith0404e012015-10-29 22:58:333787 PRE_WaitForInitialUserActivitySatisfied) {
[email protected]8e0ba06b2013-10-28 15:38:093788 // Indicate that initial user activity in this session occurred 2 hours ago.
3789 g_browser_process->local_state()->SetInt64(
3790 prefs::kSessionStartTime,
3791 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
3792 .ToInternalValue());
3793 g_browser_process->local_state()->SetBoolean(
3794 prefs::kSessionUserActivitySeen,
3795 true);
3796}
3797
[email protected]69c0c6862013-11-05 23:30:233798IN_PROC_BROWSER_TEST_F(PolicyTest,
achuith0404e012015-10-29 22:58:333799 WaitForInitialUserActivitySatisfied) {
[email protected]8e0ba06b2013-10-28 15:38:093800 content::MockNotificationObserver observer;
3801 content::NotificationRegistrar registrar;
3802 registrar.Add(&observer,
3803 chrome::NOTIFICATION_APP_TERMINATING,
3804 content::NotificationService::AllSources());
3805
3806 // Require initial user activity and set the session length limit to 3 hours.
3807 // Verify that the session is not terminated.
3808 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
3809 .Times(0);
3810 PolicyMap policies;
3811 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:093812 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303813 std::make_unique<base::Value>(true), nullptr);
dcheng3b344bc22016-05-10 02:26:093814 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
3815 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303816 std::make_unique<base::Value>(kThreeHoursInMs), nullptr);
[email protected]8e0ba06b2013-10-28 15:38:093817 UpdateProviderPolicy(policies);
3818 base::RunLoop().RunUntilIdle();
3819 Mock::VerifyAndClearExpectations(&observer);
3820
3821 // Decrease the session length limit to 1 hour. Verify that the session is
3822 // terminated immediately.
3823 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
dcheng3b344bc22016-05-10 02:26:093824 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
3825 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303826 std::make_unique<base::Value>(kOneHourInMs), nullptr);
[email protected]9a8764b2013-03-27 16:18:093827 UpdateProviderPolicy(policies);
3828 base::RunLoop().RunUntilIdle();
3829 Mock::VerifyAndClearExpectations(&observer);
3830}
[email protected]2968e4f7452013-06-10 17:39:073831
3832IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
3833 // Verifies that the large cursor accessibility feature can be controlled
3834 // through policy.
3835 chromeos::AccessibilityManager* accessibility_manager =
3836 chromeos::AccessibilityManager::Get();
3837
3838 // Manually enable the large cursor.
3839 accessibility_manager->EnableLargeCursor(true);
3840 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
3841
3842 // Verify that policy overrides the manual setting.
3843 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093844 policies.Set(key::kLargeCursorEnabled, POLICY_LEVEL_MANDATORY,
3845 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303846 std::make_unique<base::Value>(false), nullptr);
[email protected]2968e4f7452013-06-10 17:39:073847 UpdateProviderPolicy(policies);
3848 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
3849
3850 // Verify that the large cursor cannot be enabled manually anymore.
3851 accessibility_manager->EnableLargeCursor(true);
3852 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
3853}
3854
3855IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
3856 // Verifies that the spoken feedback accessibility feature can be controlled
3857 // through policy.
3858 chromeos::AccessibilityManager* accessibility_manager =
3859 chromeos::AccessibilityManager::Get();
3860
3861 // Manually enable spoken feedback.
Qiang Xu60e79032018-03-29 08:18:313862 accessibility_manager->EnableSpokenFeedback(true);
[email protected]2968e4f7452013-06-10 17:39:073863 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
3864
3865 // Verify that policy overrides the manual setting.
3866 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093867 policies.Set(key::kSpokenFeedbackEnabled, POLICY_LEVEL_MANDATORY,
3868 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303869 std::make_unique<base::Value>(false), nullptr);
[email protected]2968e4f7452013-06-10 17:39:073870 UpdateProviderPolicy(policies);
3871 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
3872
3873 // Verify that spoken feedback cannot be enabled manually anymore.
Qiang Xu60e79032018-03-29 08:18:313874 accessibility_manager->EnableSpokenFeedback(true);
[email protected]2968e4f7452013-06-10 17:39:073875 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
3876}
3877
3878IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
3879 // Verifies that the high contrast mode accessibility feature can be
3880 // controlled through policy.
3881 chromeos::AccessibilityManager* accessibility_manager =
3882 chromeos::AccessibilityManager::Get();
3883
3884 // Manually enable high contrast mode.
3885 accessibility_manager->EnableHighContrast(true);
3886 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
3887
3888 // Verify that policy overrides the manual setting.
3889 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093890 policies.Set(key::kHighContrastEnabled, POLICY_LEVEL_MANDATORY,
3891 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303892 std::make_unique<base::Value>(false), nullptr);
[email protected]2968e4f7452013-06-10 17:39:073893 UpdateProviderPolicy(policies);
3894 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
3895
3896 // Verify that high contrast mode cannot be enabled manually anymore.
3897 accessibility_manager->EnableHighContrast(true);
3898 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
3899}
3900
3901IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
3902 // Verifies that the screen magnifier can be disabled through policy.
3903 chromeos::MagnificationManager* magnification_manager =
3904 chromeos::MagnificationManager::Get();
3905
3906 // Manually enable the full-screen magnifier.
[email protected]2968e4f7452013-06-10 17:39:073907 magnification_manager->SetMagnifierEnabled(true);
[email protected]2968e4f7452013-06-10 17:39:073908 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
3909
3910 // Verify that policy overrides the manual setting.
3911 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093912 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
3913 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303914 std::make_unique<base::Value>(0), nullptr);
[email protected]2968e4f7452013-06-10 17:39:073915 UpdateProviderPolicy(policies);
3916 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
3917
3918 // Verify that the screen magnifier cannot be enabled manually anymore.
3919 magnification_manager->SetMagnifierEnabled(true);
3920 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
Anatoliy Potapchuk4b03b4702019-06-07 10:35:133921 // Verify that the docked magnifier cannot be enabled manually anymore.
3922 magnification_manager->SetDockedMagnifierEnabled(true);
3923 EXPECT_FALSE(magnification_manager->IsDockedMagnifierEnabled());
[email protected]2968e4f7452013-06-10 17:39:073924}
3925
3926IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
3927 // Verifies that the full-screen magnifier can be enabled through policy.
3928 chromeos::MagnificationManager* magnification_manager =
3929 chromeos::MagnificationManager::Get();
3930
3931 // Verify that the screen magnifier is initially disabled.
3932 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
3933
3934 // Verify that policy can enable the full-screen magnifier.
3935 PolicyMap policies;
ricea86fa1dd2016-09-13 05:59:453936 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
3937 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Qiang Xu92eabd42018-06-27 16:20:053938 std::make_unique<base::Value>(chromeos::MAGNIFIER_FULL),
3939 nullptr);
[email protected]2968e4f7452013-06-10 17:39:073940 UpdateProviderPolicy(policies);
[email protected]2968e4f7452013-06-10 17:39:073941 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
3942
3943 // Verify that the screen magnifier cannot be disabled manually anymore.
3944 magnification_manager->SetMagnifierEnabled(false);
3945 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
3946}
3947
Anatoliy Potapchuk4b03b4702019-06-07 10:35:133948IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeDocked) {
3949 // Verifies that the docked magnifier accessibility feature can be
3950 // controlled through policy.
3951 chromeos::MagnificationManager* magnification_manager =
3952 chromeos::MagnificationManager::Get();
3953
3954 // Verify that the docked magnifier is initially disabled
3955 EXPECT_FALSE(magnification_manager->IsDockedMagnifierEnabled());
3956
3957 // Verify that policy overrides the manual setting.
3958 PolicyMap policies;
3959 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
3960 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
3961 std::make_unique<base::Value>(chromeos::MAGNIFIER_DOCKED),
3962 nullptr);
3963 UpdateProviderPolicy(policies);
3964 EXPECT_TRUE(magnification_manager->IsDockedMagnifierEnabled());
3965
3966 // Verify that the docked magnifier cannot be disabled manually anymore.
3967 magnification_manager->SetDockedMagnifierEnabled(false);
3968 EXPECT_TRUE(magnification_manager->IsDockedMagnifierEnabled());
3969}
3970
[email protected]7a226972014-06-19 11:12:433971IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
[email protected]43ceb5a2014-02-14 16:40:073972 // Verifies that the on-screen keyboard accessibility feature can be
3973 // controlled through policy.
3974 chromeos::AccessibilityManager* accessibility_manager =
3975 chromeos::AccessibilityManager::Get();
3976
3977 // Manually enable the on-screen keyboard.
3978 accessibility_manager->EnableVirtualKeyboard(true);
3979 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
3980
3981 // Verify that policy overrides the manual setting.
3982 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:093983 policies.Set(key::kVirtualKeyboardEnabled, POLICY_LEVEL_MANDATORY,
3984 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:303985 std::make_unique<base::Value>(false), nullptr);
[email protected]43ceb5a2014-02-14 16:40:073986 UpdateProviderPolicy(policies);
3987 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3988
3989 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3990 accessibility_manager->EnableVirtualKeyboard(true);
3991 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3992}
3993
Amr Aboelkherbaf159842019-04-29 15:57:043994IN_PROC_BROWSER_TEST_F(PolicyTest, StickyKeysEnabled) {
3995 // Verifies that the sticky keys accessibility feature can be
3996 // controlled through policy.
3997 chromeos::AccessibilityManager* accessibility_manager =
3998 chromeos::AccessibilityManager::Get();
3999
4000 // Verify that the sticky keys is initially disabled
4001 EXPECT_FALSE(accessibility_manager->IsStickyKeysEnabled());
4002
4003 // Manually enable the sticky keys.
4004 accessibility_manager->EnableStickyKeys(true);
4005 EXPECT_TRUE(accessibility_manager->IsStickyKeysEnabled());
4006
4007 // Verify that policy overrides the manual setting.
4008 PolicyMap policies;
4009 policies.Set(key::kStickyKeysEnabled, POLICY_LEVEL_MANDATORY,
4010 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4011 std::make_unique<base::Value>(false), nullptr);
4012 UpdateProviderPolicy(policies);
4013 EXPECT_FALSE(accessibility_manager->IsStickyKeysEnabled());
4014
4015 // Verify that the sticky keys cannot be enabled manually anymore.
4016 accessibility_manager->EnableStickyKeys(true);
4017 EXPECT_FALSE(accessibility_manager->IsStickyKeysEnabled());
4018}
4019
Amr Aboelkhere6230332019-05-02 13:05:504020
[email protected]7a226972014-06-19 11:12:434021IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
Steven Bennetts34692a332018-11-10 02:11:444022 auto* keyboard_client = ChromeKeyboardControllerClient::Get();
4023 ASSERT_TRUE(keyboard_client);
4024
[email protected]7a226972014-06-19 11:12:434025 // Verify keyboard disabled by default.
Steven Bennetts34692a332018-11-10 02:11:444026 EXPECT_FALSE(keyboard_client->is_keyboard_enabled());
4027
[email protected]7a226972014-06-19 11:12:434028 // Verify keyboard can be toggled by default.
Darren Shen8604a212019-06-07 00:41:384029 SetEnableFlag(keyboard::KeyboardEnableFlag::kTouchEnabled);
Steven Bennetts34692a332018-11-10 02:11:444030 EXPECT_TRUE(keyboard_client->is_keyboard_enabled());
Darren Shen8604a212019-06-07 00:41:384031 ClearEnableFlag(keyboard::KeyboardEnableFlag::kTouchEnabled);
Steven Bennetts34692a332018-11-10 02:11:444032 EXPECT_FALSE(keyboard_client->is_keyboard_enabled());
[email protected]7a226972014-06-19 11:12:434033
4034 // Verify enabling the policy takes effect immediately and that that user
4035 // cannot disable the keyboard..
4036 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:094037 policies.Set(key::kTouchVirtualKeyboardEnabled, POLICY_LEVEL_MANDATORY,
4038 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304039 std::make_unique<base::Value>(true), nullptr);
[email protected]7a226972014-06-19 11:12:434040 UpdateProviderPolicy(policies);
Steven Bennetts34692a332018-11-10 02:11:444041 EXPECT_TRUE(keyboard_client->is_keyboard_enabled());
Darren Shen8604a212019-06-07 00:41:384042 ClearEnableFlag(keyboard::KeyboardEnableFlag::kTouchEnabled);
Steven Bennetts34692a332018-11-10 02:11:444043 EXPECT_TRUE(keyboard_client->is_keyboard_enabled());
[email protected]7a226972014-06-19 11:12:434044
4045 // Verify that disabling the policy takes effect immediately and that the user
4046 // cannot enable the keyboard.
dcheng3b344bc22016-05-10 02:26:094047 policies.Set(key::kTouchVirtualKeyboardEnabled, POLICY_LEVEL_MANDATORY,
4048 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304049 std::make_unique<base::Value>(false), nullptr);
[email protected]7a226972014-06-19 11:12:434050 UpdateProviderPolicy(policies);
Steven Bennetts34692a332018-11-10 02:11:444051 EXPECT_FALSE(keyboard_client->is_keyboard_enabled());
Darren Shen8604a212019-06-07 00:41:384052 SetEnableFlag(keyboard::KeyboardEnableFlag::kTouchEnabled);
Steven Bennetts34692a332018-11-10 02:11:444053 EXPECT_FALSE(keyboard_client->is_keyboard_enabled());
[email protected]7a226972014-06-19 11:12:434054}
4055
Yue Li74df9de2019-05-16 00:03:464056IN_PROC_BROWSER_TEST_F(PolicyTest, AssistantContextEnabled) {
4057 PrefService* prefs = browser()->profile()->GetPrefs();
4058 EXPECT_FALSE(
4059 prefs->IsManagedPreference(arc::prefs::kVoiceInteractionContextEnabled));
4060 EXPECT_FALSE(prefs->GetBoolean(arc::prefs::kVoiceInteractionContextEnabled));
4061 prefs->SetBoolean(arc::prefs::kVoiceInteractionContextEnabled, true);
4062 EXPECT_TRUE(prefs->GetBoolean(arc::prefs::kVoiceInteractionContextEnabled));
4063
4064 // Verifies that the Assistant context can be forced to always disabled.
4065 PolicyMap policies;
4066 policies.Set(key::kVoiceInteractionContextEnabled, POLICY_LEVEL_MANDATORY,
4067 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4068 std::make_unique<base::Value>(false), nullptr);
4069 UpdateProviderPolicy(policies);
4070 EXPECT_TRUE(
4071 prefs->IsManagedPreference(arc::prefs::kVoiceInteractionContextEnabled));
4072 EXPECT_FALSE(prefs->GetBoolean(arc::prefs::kVoiceInteractionContextEnabled));
4073 prefs->SetBoolean(arc::prefs::kVoiceInteractionContextEnabled, true);
4074 EXPECT_FALSE(prefs->GetBoolean(arc::prefs::kVoiceInteractionContextEnabled));
4075
4076 // Verifies that the Assistant context can be forced to always enabled.
4077 policies.Set(key::kVoiceInteractionContextEnabled, POLICY_LEVEL_MANDATORY,
4078 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4079 std::make_unique<base::Value>(true), nullptr);
4080 UpdateProviderPolicy(policies);
4081 EXPECT_TRUE(
4082 prefs->IsManagedPreference(arc::prefs::kVoiceInteractionContextEnabled));
4083 EXPECT_TRUE(prefs->GetBoolean(arc::prefs::kVoiceInteractionContextEnabled));
4084 prefs->SetBoolean(arc::prefs::kVoiceInteractionContextEnabled, false);
4085 EXPECT_TRUE(prefs->GetBoolean(arc::prefs::kVoiceInteractionContextEnabled));
4086}
4087
4088IN_PROC_BROWSER_TEST_F(PolicyTest, AssistantHotwordEnabled) {
4089 PrefService* prefs = browser()->profile()->GetPrefs();
4090 EXPECT_FALSE(
4091 prefs->IsManagedPreference(arc::prefs::kVoiceInteractionHotwordEnabled));
4092 EXPECT_FALSE(prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled));
4093 prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true);
4094 EXPECT_TRUE(prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled));
4095
4096 // Verifies that the Assistant hotword can be forced to always disabled.
4097 PolicyMap policies;
4098 policies.Set(key::kVoiceInteractionHotwordEnabled, POLICY_LEVEL_MANDATORY,
4099 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4100 std::make_unique<base::Value>(false), nullptr);
4101 UpdateProviderPolicy(policies);
4102 EXPECT_TRUE(
4103 prefs->IsManagedPreference(arc::prefs::kVoiceInteractionHotwordEnabled));
4104 EXPECT_FALSE(prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled));
4105 prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, true);
4106 EXPECT_FALSE(prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled));
4107
4108 // Verifies that the Assistant hotword can be forced to always enabled.
4109 policies.Set(key::kVoiceInteractionHotwordEnabled, POLICY_LEVEL_MANDATORY,
4110 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4111 std::make_unique<base::Value>(true), nullptr);
4112 UpdateProviderPolicy(policies);
4113 EXPECT_TRUE(
4114 prefs->IsManagedPreference(arc::prefs::kVoiceInteractionHotwordEnabled));
4115 EXPECT_TRUE(prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled));
4116 prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled, false);
4117 EXPECT_TRUE(prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled));
4118}
4119
4120#endif // defined(OS_CHROMEOS)
[email protected]7ea48702012-09-03 20:41:064121
[email protected]88ce3e72012-09-11 08:34:224122namespace {
4123
Greg Thompson2f011a452018-04-30 09:44:144124constexpr const char* kRestoredURLs[] = {
4125 "http://aaa.com/empty.html", "http://bbb.com/empty.html",
[email protected]983ac6a42013-01-18 17:22:204126};
4127
avi556c05022014-12-22 23:31:434128bool IsNonSwitchArgument(const base::CommandLine::StringType& s) {
[email protected]88ce3e72012-09-11 08:34:224129 return s.empty() || s[0] != '-';
4130}
4131
4132} // namespace
4133
4134// Similar to PolicyTest but allows setting policies before the browser is
4135// created. Each test parameter is a method that sets up the early policies
4136// and stores the expected startup URLs in |expected_urls_|.
4137class RestoreOnStartupPolicyTest
4138 : public PolicyTest,
4139 public testing::WithParamInterface<
4140 void (RestoreOnStartupPolicyTest::*)(void)> {
4141 public:
Greg Thompson146eef8c2018-06-26 09:30:544142 RestoreOnStartupPolicyTest() = default;
4143 virtual ~RestoreOnStartupPolicyTest() = default;
[email protected]88ce3e72012-09-11 08:34:224144
[email protected]2bfe6ce2012-09-13 09:47:394145#if defined(OS_CHROMEOS)
dcheng6d888df2015-01-16 18:12:484146 void SetUpCommandLine(base::CommandLine* command_line) override {
[email protected]2bfe6ce2012-09-13 09:47:394147 // TODO(nkostylev): Investigate if we can remove this switch.
4148 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
4149 PolicyTest::SetUpCommandLine(command_line);
4150 }
4151#endif
4152
dcheng32ae6bbb2014-10-22 08:47:294153 void SetUpInProcessBrowserTestFixture() override {
[email protected]88ce3e72012-09-11 08:34:224154 PolicyTest::SetUpInProcessBrowserTestFixture();
4155 // Set early policies now, before the browser is created.
4156 (this->*(GetParam()))();
4157
4158 // Remove the non-switch arguments, so that session restore kicks in for
4159 // these tests.
avi556c05022014-12-22 23:31:434160 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
4161 base::CommandLine::StringVector argv = command_line->argv();
Zhuoyu Qian779e4252019-02-14 00:45:494162 base::EraseIf(argv, IsNonSwitchArgument);
[email protected]88ce3e72012-09-11 08:34:224163 command_line->InitFromArgv(argv);
4164 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
4165 command_line->argv().begin()));
xunjieli0332c192014-09-10 23:23:314166 }
[email protected]233b688e2012-11-27 10:44:124167
dcheng32ae6bbb2014-10-22 08:47:294168 void SetUpOnMainThread() override {
Eric Seckler8652dcd52018-09-20 10:42:284169 base::PostTaskWithTraits(
4170 FROM_HERE, {BrowserThread::IO},
tzik56432d92017-04-26 05:25:254171 base::BindOnce(RedirectHostsToTestData, kRestoredURLs,
Avi Drissman5f0fb8c2018-12-25 23:20:494172 base::size(kRestoredURLs)));
[email protected]88ce3e72012-09-11 08:34:224173 }
4174
[email protected]88ce3e72012-09-11 08:34:224175 void ListOfURLs() {
4176 // Verifies that policy can set the startup pages to a list of URLs.
4177 base::ListValue urls;
Avi Drissman5f0fb8c2018-12-25 23:20:494178 for (size_t i = 0; i < base::size(kRestoredURLs); ++i) {
dchengd9ea63862016-06-03 02:27:184179 urls.AppendString(kRestoredURLs[i]);
[email protected]983ac6a42013-01-18 17:22:204180 expected_urls_.push_back(GURL(kRestoredURLs[i]));
[email protected]88ce3e72012-09-11 08:34:224181 }
4182 PolicyMap policies;
jdoerrie239723572017-03-02 12:09:194183 policies.Set(
4184 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
4185 POLICY_SOURCE_CLOUD,
4186 base::WrapUnique(new base::Value(SessionStartupPref::kPrefValueURLs)),
4187 nullptr);
dcheng3b344bc22016-05-10 02:26:094188 policies.Set(key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY,
4189 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, urls.CreateDeepCopy(),
4190 nullptr);
[email protected]88ce3e72012-09-11 08:34:224191 provider_.UpdateChromePolicy(policies);
4192 }
4193
4194 void NTP() {
4195 // Verifies that policy can set the startup page to the NTP.
4196 PolicyMap policies;
jdoerrie239723572017-03-02 12:09:194197 policies.Set(
4198 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
4199 POLICY_SOURCE_CLOUD,
4200 base::WrapUnique(new base::Value(SessionStartupPref::kPrefValueNewTab)),
4201 nullptr);
[email protected]88ce3e72012-09-11 08:34:224202 provider_.UpdateChromePolicy(policies);
[email protected]233b688e2012-11-27 10:44:124203 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
[email protected]88ce3e72012-09-11 08:34:224204 }
4205
4206 void Last() {
4207 // Verifies that policy can set the startup pages to the last session.
4208 PolicyMap policies;
jdoerrie239723572017-03-02 12:09:194209 policies.Set(
4210 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
4211 POLICY_SOURCE_CLOUD,
4212 base::WrapUnique(new base::Value(SessionStartupPref::kPrefValueLast)),
4213 nullptr);
[email protected]88ce3e72012-09-11 08:34:224214 provider_.UpdateChromePolicy(policies);
4215 // This should restore the tabs opened at PRE_RunTest below.
Avi Drissman5f0fb8c2018-12-25 23:20:494216 for (size_t i = 0; i < base::size(kRestoredURLs); ++i)
[email protected]983ac6a42013-01-18 17:22:204217 expected_urls_.push_back(GURL(kRestoredURLs[i]));
[email protected]88ce3e72012-09-11 08:34:224218 }
4219
Greg Thompson2f011a452018-04-30 09:44:144220 void Blocked() {
4221 // Verifies that URLs are blocked during session restore.
4222 PolicyMap policies;
4223 policies.Set(
4224 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
4225 POLICY_SOURCE_CLOUD,
4226 std::make_unique<base::Value>(SessionStartupPref::kPrefValueLast),
4227 nullptr);
4228 auto urls = std::make_unique<base::Value>(base::Value::Type::LIST);
4229 for (const auto* url_string : kRestoredURLs)
4230 urls->GetList().emplace_back(url_string);
4231 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
4232 POLICY_SOURCE_CLOUD, std::move(urls), nullptr);
4233 provider_.UpdateChromePolicy(policies);
4234 // This should restore the tabs opened at PRE_RunTest below, yet all should
4235 // be blocked.
4236 blocked_ = true;
Avi Drissman5f0fb8c2018-12-25 23:20:494237 for (size_t i = 0; i < base::size(kRestoredURLs); ++i)
Greg Thompson2f011a452018-04-30 09:44:144238 expected_urls_.emplace_back(kRestoredURLs[i]);
4239 }
4240
4241 // URLs that are expected to be loaded.
[email protected]88ce3e72012-09-11 08:34:224242 std::vector<GURL> expected_urls_;
Greg Thompson2f011a452018-04-30 09:44:144243
4244 // True if the loaded URLs should be blocked by policy.
4245 bool blocked_ = false;
[email protected]88ce3e72012-09-11 08:34:224246};
4247
4248IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
tmartinof9a9ef142017-02-01 21:11:074249 // Do not show Welcome Page.
4250 browser()->profile()->GetPrefs()->SetBoolean(prefs::kHasSeenWelcomePage,
4251 true);
4252
[email protected]88ce3e72012-09-11 08:34:224253 // Open some tabs to verify if they are restored after the browser restarts.
4254 // Most policy settings override this, except kPrefValueLast which enforces
4255 // a restore.
[email protected]983ac6a42013-01-18 17:22:204256 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
Avi Drissman5f0fb8c2018-12-25 23:20:494257 for (size_t i = 1; i < base::size(kRestoredURLs); ++i) {
[email protected]19506d542013-10-15 23:11:064258 content::WindowedNotificationObserver observer(
4259 content::NOTIFICATION_LOAD_STOP,
4260 content::NotificationService::AllSources());
4261 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
Sylvain Defresnec6ccc77d2014-09-19 10:19:354262 ui::PAGE_TRANSITION_LINK);
[email protected]19506d542013-10-15 23:11:064263 observer.Wait();
[email protected]88ce3e72012-09-11 08:34:224264 }
4265}
4266
Greg Thompson2f011a452018-04-30 09:44:144267// Flaky on Linux; see https://crbug.com/701023.
4268#if defined(OS_LINUX)
4269#define MAYBE_RunTest DISABLED_RunTest
4270#else
4271#define MAYBE_RunTest RunTest
4272#endif
4273IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, MAYBE_RunTest) {
[email protected]88ce3e72012-09-11 08:34:224274 TabStripModel* model = browser()->tab_strip_model();
4275 int size = static_cast<int>(expected_urls_.size());
4276 EXPECT_EQ(size, model->count());
Francois Doray8059c542018-07-05 21:16:204277 resource_coordinator::WaitForTransitionToLoaded(model);
[email protected]88ce3e72012-09-11 08:34:224278 for (int i = 0; i < size && i < model->count(); ++i) {
Greg Thompson2f011a452018-04-30 09:44:144279 content::WebContents* web_contents = model->GetWebContentsAt(i);
Greg Thompson2f011a452018-04-30 09:44:144280 if (blocked_)
4281 CheckURLIsBlockedInWebContents(web_contents, expected_urls_[i]);
4282 else if (expected_urls_[i] == GURL(chrome::kChromeUINewTabURL))
4283 EXPECT_TRUE(search::IsInstantNTP(web_contents));
4284 else
4285 EXPECT_EQ(expected_urls_[i], web_contents->GetURL());
[email protected]88ce3e72012-09-11 08:34:224286 }
4287}
Greg Thompsona37b35b2018-06-29 11:35:444288#undef MAYBE_RunTest
[email protected]88ce3e72012-09-11 08:34:224289
Victor Costane5e91512019-02-13 08:24:024290INSTANTIATE_TEST_SUITE_P(
4291 RestoreOnStartupPolicyTestInstance,
4292 RestoreOnStartupPolicyTest,
4293 testing::Values(&RestoreOnStartupPolicyTest::ListOfURLs,
4294 &RestoreOnStartupPolicyTest::NTP,
4295 &RestoreOnStartupPolicyTest::Last,
4296 &RestoreOnStartupPolicyTest::Blocked));
[email protected]88ce3e72012-09-11 08:34:224297
[email protected]09f6906e2012-10-12 10:49:024298// Similar to PolicyTest but sets a couple of policies before the browser is
4299// started.
4300class PolicyStatisticsCollectorTest : public PolicyTest {
4301 public:
4302 PolicyStatisticsCollectorTest() {}
dchenge1bc7982014-10-30 00:32:404303 ~PolicyStatisticsCollectorTest() override {}
[email protected]09f6906e2012-10-12 10:49:024304
dcheng32ae6bbb2014-10-22 08:47:294305 void SetUpInProcessBrowserTestFixture() override {
[email protected]09f6906e2012-10-12 10:49:024306 PolicyTest::SetUpInProcessBrowserTestFixture();
4307 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:094308 policies.Set(key::kShowHomeButton, POLICY_LEVEL_MANDATORY,
4309 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304310 std::make_unique<base::Value>(true), nullptr);
dcheng3b344bc22016-05-10 02:26:094311 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
4312 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304313 std::make_unique<base::Value>(false), nullptr);
dcheng3b344bc22016-05-10 02:26:094314 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
4315 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304316 std::make_unique<base::Value>("http://chromium.org"), nullptr);
[email protected]09f6906e2012-10-12 10:49:024317 provider_.UpdateChromePolicy(policies);
4318 }
4319};
4320
4321IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
4322 // Verifies that policy usage histograms are collected at startup.
4323
4324 // BrowserPolicyConnector::Init() has already been called. Make sure the
4325 // CompleteInitialization() task has executed as well.
4326 content::RunAllPendingInMessageLoop();
4327
Mathieu Perreault18170a42018-05-17 12:48:154328 base::HistogramBase* histogram =
4329 base::StatisticsRecorder::FindHistogram("Enterprise.Policies");
4330 std::unique_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
[email protected]09f6906e2012-10-12 10:49:024331 // HomepageLocation has policy ID 1.
Mathieu Perreault18170a42018-05-17 12:48:154332 EXPECT_GT(samples->GetCount(1), 0);
[email protected]09f6906e2012-10-12 10:49:024333 // ShowHomeButton has policy ID 35.
Mathieu Perreault18170a42018-05-17 12:48:154334 EXPECT_GT(samples->GetCount(35), 0);
[email protected]09f6906e2012-10-12 10:49:024335 // BookmarkBarEnabled has policy ID 82.
Mathieu Perreault18170a42018-05-17 12:48:154336 EXPECT_GT(samples->GetCount(82), 0);
[email protected]09f6906e2012-10-12 10:49:024337}
4338
Weilun Shib59ba592018-08-07 22:42:354339// Similar to PolicyTest, but force to enable the new tab material design flag
4340// before the browser start.
4341class PolicyWebStoreIconTest : public PolicyTest {
4342 public:
4343 PolicyWebStoreIconTest() {}
4344 ~PolicyWebStoreIconTest() override {}
4345
4346 void SetUpInProcessBrowserTestFixture() override {
4347 PolicyTest::SetUpInProcessBrowserTestFixture();
4348 }
4349
4350 void SetUpCommandLine(base::CommandLine* command_line) override {
4351 PolicyTest::SetUpCommandLine(command_line);
Weilun Shib59ba592018-08-07 22:42:354352 }
4353
4354 private:
Sorin Jianu55587d32018-11-14 21:43:274355 DISALLOW_COPY_AND_ASSIGN(PolicyWebStoreIconTest);
Weilun Shib59ba592018-08-07 22:42:354356};
4357
4358IN_PROC_BROWSER_TEST_F(PolicyWebStoreIconTest, AppsWebStoreIconHidden) {
4359 // Verifies that the web store icon can be hidden from the chrome://apps
4360 // page. A policy change takes immediate effect on the apps page for the
4361 // current profile. Browser restart is not required.
4362
4363 // Open new tab page and look for the web store icons.
4364 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAppsURL));
4365 content::WebContents* contents =
4366 browser()->tab_strip_model()->GetActiveWebContents();
4367
4368#if !defined(OS_CHROMEOS)
4369 // Look for web store's app ID in the apps page.
4370 EXPECT_TRUE(
4371 ContainsVisibleElement(contents, "ahfgeienlihckogmohjhadlkjgocpleb"));
4372#endif
4373
4374 // The next NTP has no footer.
4375 if (ContainsVisibleElement(contents, "footer"))
4376 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
4377
4378 // Turn off the web store icons.
4379 PolicyMap policies;
4380 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
4381 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4382 base::WrapUnique(new base::Value(true)), nullptr);
4383 UpdateProviderPolicy(policies);
4384
4385 // The web store icons should now be hidden.
4386 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAppsURL));
4387 EXPECT_FALSE(
4388 ContainsVisibleElement(contents, "ahfgeienlihckogmohjhadlkjgocpleb"));
4389 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
4390}
4391
4392IN_PROC_BROWSER_TEST_F(PolicyWebStoreIconTest, NTPWebStoreIconShown) {
4393 // This test is to verify that the web store icons is shown when no policy
4394 // applies. See WebStoreIconPolicyTest.NTPWebStoreIconHidden for verification
4395 // when a policy is in effect.
4396
Weilun Shib59ba592018-08-07 22:42:354397 // Open new tab page and look for the web store icons.
4398 content::WebContents* active_tab =
4399 local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
4400 local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
4401
4402 content::RenderFrameHost* iframe = GetMostVisitedIframe(active_tab);
4403
4404 // Look though all the tiles and see whether there is a webstore icon.
4405 // Make sure that there is one web store icon.
4406 EXPECT_TRUE(ContainsWebstoreTile(iframe));
4407}
4408
4409// Similar to PolicyWebStoreIconShownTest, but applies the HideWebStoreIcon
4410// policy before the browser is started. This is required because the list that
4411// includes the WebStoreIcon on the NTP is initialized at browser start.
4412class PolicyWebStoreIconHiddenTest : public PolicyTest {
4413 public:
4414 PolicyWebStoreIconHiddenTest() {}
4415 ~PolicyWebStoreIconHiddenTest() override {}
4416
4417 void SetUpInProcessBrowserTestFixture() override {
4418 PolicyTest::SetUpInProcessBrowserTestFixture();
4419 PolicyMap policies;
4420 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
4421 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4422 std::make_unique<base::Value>(true), nullptr);
4423 provider_.UpdateChromePolicy(policies);
4424 }
4425
4426 void SetUpCommandLine(base::CommandLine* command_line) override {
4427 PolicyTest::SetUpCommandLine(command_line);
Weilun Shib59ba592018-08-07 22:42:354428 }
4429
4430 private:
Sorin Jianu55587d32018-11-14 21:43:274431 DISALLOW_COPY_AND_ASSIGN(PolicyWebStoreIconHiddenTest);
Weilun Shib59ba592018-08-07 22:42:354432};
4433
4434IN_PROC_BROWSER_TEST_F(PolicyWebStoreIconHiddenTest, NTPWebStoreIconHidden) {
4435 // Verifies that the web store icon can be hidden from the new tab page. Check
4436 // to see NTPWebStoreIconShown for behavior when the policy is not applied.
4437
4438 // Open new tab page and look for the web store icon
4439 content::WebContents* active_tab =
4440 local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank"));
4441 local_ntp_test_utils::NavigateToNTPAndWaitUntilLoaded(browser());
4442
4443 content::RenderFrameHost* iframe = GetMostVisitedIframe(active_tab);
4444
4445 // Applying the policy before the browser started, the web store icon should
4446 // now be hidden.
4447 EXPECT_FALSE(ContainsWebstoreTile(iframe));
4448}
4449
[email protected]4ee5604f2013-01-24 14:43:504450class MediaStreamDevicesControllerBrowserTest
4451 : public PolicyTest,
4452 public testing::WithParamInterface<bool> {
4453 public:
[email protected]e2d31402013-05-28 15:26:204454 MediaStreamDevicesControllerBrowserTest()
Raymes Khourya9873a152017-10-23 07:15:084455 : request_url_allowed_via_whitelist_(false) {
[email protected]4ee5604f2013-01-24 14:43:504456 policy_value_ = GetParam();
4457 }
4458 virtual ~MediaStreamDevicesControllerBrowserTest() {}
4459
raymes3bc708e2017-04-11 00:38:244460 void SetUpOnMainThread() override {
4461 PolicyTest::SetUpOnMainThread();
Raymes Khourya9873a152017-10-23 07:15:084462
4463 ASSERT_TRUE(embedded_test_server()->Start());
4464 request_url_ = embedded_test_server()->GetURL("/simple.html");
4465 request_pattern_ = request_url_.GetOrigin().spec();
raymes3bc708e2017-04-11 00:38:244466 ui_test_utils::NavigateToURL(browser(), request_url_);
timlohfa10d432017-06-20 00:50:234467
4468 // Testing both the new (PermissionManager) and old code-paths is not simple
4469 // since we are already using WithParamInterface. We only test whichever one
4470 // is enabled in chrome_features.cc since we won't keep the old path around
4471 // for long once we flip the flag.
Timothy Loh8786fb32017-09-06 03:04:054472 PermissionRequestManager* manager =
4473 PermissionRequestManager::FromWebContents(
4474 browser()->tab_strip_model()->GetActiveWebContents());
4475 prompt_factory_.reset(new MockPermissionPromptFactory(manager));
4476 prompt_factory_->set_response_type(PermissionRequestManager::ACCEPT_ALL);
raymes3bc708e2017-04-11 00:38:244477 }
4478
timlohfa10d432017-06-20 00:50:234479 void TearDownOnMainThread() override { prompt_factory_.reset(); }
4480
raymes3bc708e2017-04-11 00:38:244481 content::MediaStreamRequest CreateRequest(
Antonio Gomesc8b734b2019-06-05 18:22:164482 blink::mojom::MediaStreamType audio_request_type,
4483 blink::mojom::MediaStreamType video_request_type) {
raymes3bc708e2017-04-11 00:38:244484 content::WebContents* web_contents =
4485 browser()->tab_strip_model()->GetActiveWebContents();
4486 EXPECT_EQ(request_url_,
4487 web_contents->GetMainFrame()->GetLastCommittedURL());
Lukasz Anforowicz0e9fdcd2017-09-28 13:00:034488 int render_process_id = web_contents->GetMainFrame()->GetProcess()->GetID();
raymes3bc708e2017-04-11 00:38:244489 int render_frame_id = web_contents->GetMainFrame()->GetRoutingID();
4490 return content::MediaStreamRequest(
4491 render_process_id, render_frame_id, 0, request_url_.GetOrigin(), false,
Guido Urdaneta73fa6632019-01-14 18:46:264492 blink::MEDIA_DEVICE_ACCESS, std::string(), std::string(),
raymes3bc708e2017-04-11 00:38:244493 audio_request_type, video_request_type, false);
4494 }
4495
raymes8a2eb0462015-07-06 01:54:094496 // Configure a given policy map. The |policy_name| is the name of either the
4497 // audio or video capture allow policy and must never be NULL.
[email protected]e2d31402013-05-28 15:26:204498 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
raymes8a2eb0462015-07-06 01:54:094499 // policy is set. If non-NULL, the whitelist policy is set to contain either
4500 // the |allow_rule| (if non-NULL) or an "allow all" wildcard.
[email protected]e2d31402013-05-28 15:26:204501 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
4502 const char* whitelist_policy,
4503 const char* allow_rule) {
dcheng3b344bc22016-05-10 02:26:094504 policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
fhorschig64834b712015-09-21 14:20:234505 POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304506 std::make_unique<base::Value>(policy_value_), nullptr);
[email protected]e2d31402013-05-28 15:26:204507
4508 if (whitelist_policy) {
[email protected]e2d31402013-05-28 15:26:204509 // Add an entry to the whitelist that allows the specified URL regardless
4510 // of the setting of kAudioCapturedAllowed.
dcheng3b344bc22016-05-10 02:26:094511 std::unique_ptr<base::ListValue> list(new base::ListValue);
[email protected]e2d31402013-05-28 15:26:204512 if (allow_rule) {
4513 list->AppendString(allow_rule);
4514 request_url_allowed_via_whitelist_ = true;
4515 } else {
4516 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
4517 // We should ignore all wildcard entries in the whitelist, so even
4518 // though we've added an entry, it should be ignored and our expectation
4519 // is that the request has not been allowed via the whitelist.
4520 request_url_allowed_via_whitelist_ = false;
4521 }
fhorschig64834b712015-09-21 14:20:234522 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
dcheng3b344bc22016-05-10 02:26:094523 POLICY_SOURCE_CLOUD, std::move(list), nullptr);
[email protected]e2d31402013-05-28 15:26:204524 }
4525 }
4526
Guido Urdaneta73fa6632019-01-14 18:46:264527 void Accept(const blink::MediaStreamDevices& devices,
Antonio Gomes0d42960a2019-06-05 12:35:514528 blink::mojom::MediaStreamRequestResult result,
dcheng08cfe9ba2016-04-14 17:46:454529 std::unique_ptr<content::MediaStreamUI> ui) {
[email protected]e2d31402013-05-28 15:26:204530 if (policy_value_ || request_url_allowed_via_whitelist_) {
[email protected]4ee5604f2013-01-24 14:43:504531 ASSERT_EQ(1U, devices.size());
4532 ASSERT_EQ("fake_dev", devices[0].id);
4533 } else {
4534 ASSERT_EQ(0U, devices.size());
4535 }
4536 }
4537
4538 void FinishAudioTest() {
Antonio Gomesc8b734b2019-06-05 18:22:164539 content::MediaStreamRequest request(
4540 CreateRequest(blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE,
4541 blink::mojom::MediaStreamType::NO_SERVICE));
[email protected]ae6ef142013-06-13 22:50:524542 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
4543 // and microphone permissions at the same time.
Timothy Loh8786fb32017-09-06 03:04:054544 MediaStreamDevicesController::RequestPermissions(
4545 request, base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept,
4546 base::Unretained(this)));
[email protected]4ee5604f2013-01-24 14:43:504547
Gabriel Charette53a9ef812017-07-26 12:36:234548 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]4ee5604f2013-01-24 14:43:504549 }
4550
4551 void FinishVideoTest() {
Antonio Gomesc8b734b2019-06-05 18:22:164552 content::MediaStreamRequest request(
4553 CreateRequest(blink::mojom::MediaStreamType::NO_SERVICE,
4554 blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE));
raymes8a2eb0462015-07-06 01:54:094555 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
4556 // and microphone permissions at the same time.
Timothy Loh8786fb32017-09-06 03:04:054557 MediaStreamDevicesController::RequestPermissions(
4558 request, base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept,
4559 base::Unretained(this)));
[email protected]4ee5604f2013-01-24 14:43:504560
Gabriel Charette53a9ef812017-07-26 12:36:234561 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]4ee5604f2013-01-24 14:43:504562 }
4563
timlohfa10d432017-06-20 00:50:234564 std::unique_ptr<MockPermissionPromptFactory> prompt_factory_;
[email protected]4ee5604f2013-01-24 14:43:504565 bool policy_value_;
[email protected]e2d31402013-05-28 15:26:204566 bool request_url_allowed_via_whitelist_;
4567 GURL request_url_;
Raymes Khourya9873a152017-10-23 07:15:084568 std::string request_pattern_;
[email protected]4ee5604f2013-01-24 14:43:504569};
4570
4571IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
4572 AudioCaptureAllowed) {
Guido Urdaneta73fa6632019-01-14 18:46:264573 blink::MediaStreamDevices audio_devices;
Antonio Gomesc8b734b2019-06-05 18:22:164574 blink::MediaStreamDevice fake_audio_device(
4575 blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE, "fake_dev",
4576 "Fake Audio Device");
[email protected]4ee5604f2013-01-24 14:43:504577 audio_devices.push_back(fake_audio_device);
4578
4579 PolicyMap policies;
[email protected]e2d31402013-05-28 15:26:204580 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
[email protected]4ee5604f2013-01-24 14:43:504581 UpdateProviderPolicy(policies);
4582
Eric Seckler8652dcd52018-09-20 10:42:284583 base::PostTaskWithTraitsAndReply(
4584 FROM_HERE, {content::BrowserThread::IO},
tzik56432d92017-04-26 05:25:254585 base::BindOnce(
4586 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
4587 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
4588 audio_devices),
4589 base::BindOnce(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
4590 base::Unretained(this)));
[email protected]4ee5604f2013-01-24 14:43:504591
fdoraycb32419d2016-06-23 15:52:554592 base::RunLoop().Run();
[email protected]4ee5604f2013-01-24 14:43:504593}
4594
4595IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
[email protected]e2d31402013-05-28 15:26:204596 AudioCaptureAllowedUrls) {
Guido Urdaneta73fa6632019-01-14 18:46:264597 blink::MediaStreamDevices audio_devices;
Antonio Gomesc8b734b2019-06-05 18:22:164598 blink::MediaStreamDevice fake_audio_device(
4599 blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE, "fake_dev",
4600 "Fake Audio Device");
[email protected]e2d31402013-05-28 15:26:204601 audio_devices.push_back(fake_audio_device);
4602
4603 const char* allow_pattern[] = {
Raymes Khourya9873a152017-10-23 07:15:084604 request_pattern_.c_str(),
4605 // This will set an allow-all policy whitelist. Since we do not allow
4606 // setting an allow-all entry in the whitelist, this entry should be
4607 // ignored and therefore the request should be denied.
4608 nullptr,
[email protected]e2d31402013-05-28 15:26:204609 };
4610
Avi Drissman5f0fb8c2018-12-25 23:20:494611 for (size_t i = 0; i < base::size(allow_pattern); ++i) {
[email protected]e2d31402013-05-28 15:26:204612 PolicyMap policies;
4613 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
4614 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
4615 UpdateProviderPolicy(policies);
4616
Eric Seckler8652dcd52018-09-20 10:42:284617 base::PostTaskWithTraitsAndReply(
4618 FROM_HERE, {content::BrowserThread::IO},
tzik56432d92017-04-26 05:25:254619 base::BindOnce(
[email protected]060ffdb2014-03-14 21:09:374620 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
[email protected]e2d31402013-05-28 15:26:204621 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
4622 audio_devices),
tzik56432d92017-04-26 05:25:254623 base::BindOnce(
[email protected]e2d31402013-05-28 15:26:204624 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
tzike04a1472016-08-02 21:00:334625 base::Unretained(this)));
[email protected]e2d31402013-05-28 15:26:204626
fdoraycb32419d2016-06-23 15:52:554627 base::RunLoop().Run();
[email protected]e2d31402013-05-28 15:26:204628 }
4629}
4630
4631IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
[email protected]4ee5604f2013-01-24 14:43:504632 VideoCaptureAllowed) {
Guido Urdaneta73fa6632019-01-14 18:46:264633 blink::MediaStreamDevices video_devices;
Antonio Gomesc8b734b2019-06-05 18:22:164634 blink::MediaStreamDevice fake_video_device(
4635 blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, "fake_dev",
4636 "Fake Video Device");
[email protected]4ee5604f2013-01-24 14:43:504637 video_devices.push_back(fake_video_device);
4638
4639 PolicyMap policies;
[email protected]e2d31402013-05-28 15:26:204640 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
[email protected]4ee5604f2013-01-24 14:43:504641 UpdateProviderPolicy(policies);
4642
Eric Seckler8652dcd52018-09-20 10:42:284643 base::PostTaskWithTraitsAndReply(
4644 FROM_HERE, {content::BrowserThread::IO},
tzik56432d92017-04-26 05:25:254645 base::BindOnce(
4646 &MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
4647 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
4648 video_devices),
4649 base::BindOnce(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
4650 base::Unretained(this)));
[email protected]4ee5604f2013-01-24 14:43:504651
fdoraycb32419d2016-06-23 15:52:554652 base::RunLoop().Run();
[email protected]4ee5604f2013-01-24 14:43:504653}
4654
[email protected]e2d31402013-05-28 15:26:204655IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
4656 VideoCaptureAllowedUrls) {
Guido Urdaneta73fa6632019-01-14 18:46:264657 blink::MediaStreamDevices video_devices;
Antonio Gomesc8b734b2019-06-05 18:22:164658 blink::MediaStreamDevice fake_video_device(
4659 blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, "fake_dev",
4660 "Fake Video Device");
[email protected]e2d31402013-05-28 15:26:204661 video_devices.push_back(fake_video_device);
4662
4663 const char* allow_pattern[] = {
Raymes Khourya9873a152017-10-23 07:15:084664 request_pattern_.c_str(),
4665 // This will set an allow-all policy whitelist. Since we do not allow
4666 // setting an allow-all entry in the whitelist, this entry should be
4667 // ignored and therefore the request should be denied.
4668 nullptr,
[email protected]e2d31402013-05-28 15:26:204669 };
4670
Avi Drissman5f0fb8c2018-12-25 23:20:494671 for (size_t i = 0; i < base::size(allow_pattern); ++i) {
[email protected]e2d31402013-05-28 15:26:204672 PolicyMap policies;
4673 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
4674 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
4675 UpdateProviderPolicy(policies);
4676
Eric Seckler8652dcd52018-09-20 10:42:284677 base::PostTaskWithTraitsAndReply(
4678 FROM_HERE, {content::BrowserThread::IO},
tzik56432d92017-04-26 05:25:254679 base::BindOnce(
4680 &MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
[email protected]e2d31402013-05-28 15:26:204681 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
4682 video_devices),
tzik56432d92017-04-26 05:25:254683 base::BindOnce(
[email protected]e2d31402013-05-28 15:26:204684 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
tzike04a1472016-08-02 21:00:334685 base::Unretained(this)));
[email protected]e2d31402013-05-28 15:26:204686
fdoraycb32419d2016-06-23 15:52:554687 base::RunLoop().Run();
[email protected]e2d31402013-05-28 15:26:204688 }
4689}
4690
Victor Costane5e91512019-02-13 08:24:024691INSTANTIATE_TEST_SUITE_P(MediaStreamDevicesControllerBrowserTestInstance,
4692 MediaStreamDevicesControllerBrowserTest,
4693 testing::Bool());
[email protected]4ee5604f2013-01-24 14:43:504694
jyasskin98bdd3992016-02-26 20:25:454695class WebBluetoothPolicyTest : public PolicyTest {
4696 void SetUpCommandLine(base::CommandLine* command_line)override {
juncai3ad09e102016-10-28 03:08:064697 // TODO(juncai): Remove this switch once Web Bluetooth is supported on Linux
4698 // and Windows.
4699 // https://crbug.com/570344
4700 // https://crbug.com/507419
4701 command_line->AppendSwitch(
4702 switches::kEnableExperimentalWebPlatformFeatures);
jyasskin98bdd3992016-02-26 20:25:454703 PolicyTest::SetUpCommandLine(command_line);
4704 }
4705};
4706
4707IN_PROC_BROWSER_TEST_F(WebBluetoothPolicyTest, Block) {
4708 // Fake the BluetoothAdapter to say it's present.
4709 scoped_refptr<device::MockBluetoothAdapter> adapter =
4710 new testing::NiceMock<device::MockBluetoothAdapter>;
4711 EXPECT_CALL(*adapter, IsPresent()).WillRepeatedly(testing::Return(true));
ortuno63120472017-05-02 23:34:534712 auto bt_global_values =
4713 device::BluetoothAdapterFactory::Get().InitGlobalValuesForTesting();
4714 bt_global_values->SetLESupported(true);
jyasskin98bdd3992016-02-26 20:25:454715 device::BluetoothAdapterFactory::SetAdapterForTesting(adapter);
4716
4717 // Navigate to a secure context.
4718 embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
4719 ASSERT_TRUE(embedded_test_server()->Start());
4720 ui_test_utils::NavigateToURL(
4721 browser(),
4722 embedded_test_server()->GetURL("localhost", "/simple_page.html"));
4723 content::WebContents* const web_contents =
4724 browser()->tab_strip_model()->GetActiveWebContents();
4725 EXPECT_THAT(
4726 web_contents->GetMainFrame()->GetLastCommittedOrigin().Serialize(),
4727 testing::StartsWith("http://localhost:"));
4728
4729 // Set the policy to block Web Bluetooth.
4730 PolicyMap policies;
4731 policies.Set(key::kDefaultWebBluetoothGuardSetting, POLICY_LEVEL_MANDATORY,
4732 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:304733 std::make_unique<base::Value>(2), nullptr);
jyasskin98bdd3992016-02-26 20:25:454734 UpdateProviderPolicy(policies);
4735
4736 std::string rejection;
4737 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
4738 web_contents,
4739 "navigator.bluetooth.requestDevice({filters: [{name: 'Hello'}]})"
4740 " .then(() => { domAutomationController.send('Success'); },"
4741 " reason => {"
4742 " domAutomationController.send(reason.name + ': ' + reason.message);"
4743 " });",
4744 &rejection));
4745 EXPECT_THAT(rejection, testing::MatchesRegex("NotFoundError: .*policy.*"));
4746}
4747
Carlos IL5a9e7512019-06-13 22:35:284748IN_PROC_BROWSER_TEST_F(PolicyTest,
rsleevi96356f82016-06-30 09:01:204749 CertificateTransparencyEnforcementDisabledForUrls) {
rsleevi96356f82016-06-30 09:01:204750 net::EmbeddedTestServer https_server_ok(net::EmbeddedTestServer::TYPE_HTTPS);
4751 https_server_ok.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
4752 https_server_ok.ServeFilesFromSourceDirectory("chrome/test/data");
4753 ASSERT_TRUE(https_server_ok.Start());
4754
4755 // Require CT for all hosts (in the absence of policy).
Doug Turner9e79cf0c2018-04-05 21:32:304756 bool required = true;
4757 SetShouldRequireCTForTesting(&required);
rsleevi96356f82016-06-30 09:01:204758
4759 ui_test_utils::NavigateToURL(browser(), https_server_ok.GetURL("/"));
4760
4761 // The page should initially be blocked.
Carlos IL0ea4e592018-05-11 01:51:574762 content::WebContents* tab =
4763 browser()->tab_strip_model()->GetActiveWebContents();
4764 WaitForInterstitial(tab);
rsleevi96356f82016-06-30 09:01:204765
4766 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
Carlos IL5a9e7512019-06-13 22:35:284767 tab->GetMainFrame(), "proceed-link"));
rsleevi96356f82016-06-30 09:01:204768 EXPECT_NE(base::UTF8ToUTF16("OK"),
4769 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
4770
4771 // Now exempt the URL from being blocked by setting policy.
4772 std::unique_ptr<base::ListValue> disabled_urls =
Jinho Bang2a491912018-01-16 07:21:304773 std::make_unique<base::ListValue>();
rsleevi96356f82016-06-30 09:01:204774 disabled_urls->AppendString(https_server_ok.host_port_pair().HostForURL());
4775
4776 PolicyMap policies;
4777 policies.Set(key::kCertificateTransparencyEnforcementDisabledForUrls,
4778 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4779 std::move(disabled_urls), nullptr);
4780 UpdateProviderPolicy(policies);
4781 FlushBlacklistPolicy();
4782
4783 ui_test_utils::NavigateToURL(browser(),
4784 https_server_ok.GetURL("/simple.html"));
4785
4786 // There should be no interstitial after the page loads.
Carlos IL0ea4e592018-05-11 01:51:574787 EXPECT_FALSE(IsShowingInterstitial(tab));
rsleevi96356f82016-06-30 09:01:204788 EXPECT_EQ(base::UTF8ToUTF16("OK"),
4789 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
John Abd-El-Malek39d0a672018-09-28 22:14:054790
4791 // Now ensure that this setting still works after a network process crash.
John Abd-El-Malek9dba1ad2018-10-27 02:22:144792 if (!content::IsOutOfProcessNetworkService())
John Abd-El-Malek39d0a672018-09-28 22:14:054793 return;
John Abd-El-Malek39d0a672018-09-28 22:14:054794
4795 ui_test_utils::NavigateToURL(browser(),
4796 https_server_ok.GetURL("/title1.html"));
4797
4798 SimulateNetworkServiceCrash();
4799 SetShouldRequireCTForTesting(&required);
4800
4801 ui_test_utils::NavigateToURL(browser(),
4802 https_server_ok.GetURL("/simple.html"));
4803
4804 // There should be no interstitial after the page loads.
4805 EXPECT_FALSE(IsShowingInterstitial(tab));
4806 EXPECT_EQ(base::UTF8ToUTF16("OK"),
4807 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
rsleevi96356f82016-06-30 09:01:204808}
4809
Ryan Sleevic8889d02018-04-06 17:57:054810IN_PROC_BROWSER_TEST_F(PolicyTest,
4811 CertificateTransparencyEnforcementDisabledForCas) {
4812 net::EmbeddedTestServer https_server_ok(net::EmbeddedTestServer::TYPE_HTTPS);
4813 https_server_ok.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
4814 https_server_ok.ServeFilesFromSourceDirectory("chrome/test/data");
4815 ASSERT_TRUE(https_server_ok.Start());
4816
4817 // Require CT for all hosts (in the absence of policy).
4818 bool required = true;
4819 SetShouldRequireCTForTesting(&required);
4820
4821 ui_test_utils::NavigateToURL(browser(), https_server_ok.GetURL("/"));
4822
Carlos IL798c47c8ce2018-11-26 17:30:414823 content::WebContents* web_contents =
4824 browser()->tab_strip_model()->GetActiveWebContents();
Carlos ILa1b9cd32018-11-20 01:21:554825
Carlos IL798c47c8ce2018-11-26 17:30:414826 // The page should initially be blocked.
4827 content::RenderFrameHost* main_frame;
Carlos IL5a9e7512019-06-13 22:35:284828 security_interstitials::SecurityInterstitialTabHelper* helper =
4829 security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
4830 web_contents);
4831 ASSERT_TRUE(helper);
4832 ASSERT_TRUE(
4833 helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting());
4834 main_frame = web_contents->GetMainFrame();
Carlos IL798c47c8ce2018-11-26 17:30:414835 ASSERT_TRUE(content::WaitForRenderFrameReady(main_frame));
Maxim Kolosovskiy32607172018-11-20 10:09:214836 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
Carlos IL798c47c8ce2018-11-26 17:30:414837 main_frame, "proceed-link"));
4838
Ryan Sleevic8889d02018-04-06 17:57:054839 EXPECT_NE(base::UTF8ToUTF16("OK"),
4840 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
4841
4842 // Now exempt the leaf SPKI from being blocked by setting policy.
4843 net::HashValue leaf_hash;
4844 ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash(
4845 https_server_ok.GetCertificate()->cert_buffer(), &leaf_hash));
4846 std::unique_ptr<base::ListValue> disabled_spkis =
4847 std::make_unique<base::ListValue>();
4848 disabled_spkis->AppendString(leaf_hash.ToString());
4849
4850 PolicyMap policies;
4851 policies.Set(key::kCertificateTransparencyEnforcementDisabledForCas,
4852 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4853 std::move(disabled_spkis), nullptr);
4854 UpdateProviderPolicy(policies);
4855 FlushBlacklistPolicy();
4856
4857 ui_test_utils::NavigateToURL(browser(),
4858 https_server_ok.GetURL("/simple.html"));
4859
Carlos IL5a9e7512019-06-13 22:35:284860 // Check we are no longer in the interstitial.
Ryan Sleevic8889d02018-04-06 17:57:054861 EXPECT_EQ(base::UTF8ToUTF16("OK"),
4862 browser()->tab_strip_model()->GetActiveWebContents()->GetTitle());
4863}
4864
estark86642d602015-04-09 20:39:164865// Test that when extended reporting opt-in is disabled by policy, the
4866// opt-in checkbox does not appear on SSL blocking pages.
Luke Zielinski47a92852018-03-01 20:42:574867// Note: SafeBrowsingExtendedReportingOptInAllowed policy is being deprecated.
Carlos IL5a9e7512019-06-13 22:35:284868IN_PROC_BROWSER_TEST_F(PolicyTest, SafeBrowsingExtendedReportingOptInAllowed) {
svaldeza01f7d92015-11-18 17:47:564869 net::EmbeddedTestServer https_server_expired(
4870 net::EmbeddedTestServer::TYPE_HTTPS);
4871 https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
4872 https_server_expired.ServeFilesFromSourceDirectory("chrome/test/data");
estark86642d602015-04-09 20:39:164873 ASSERT_TRUE(https_server_expired.Start());
4874
Luke Zielinski389909fa2018-06-10 02:10:564875 // First, navigate to an SSL error page and make sure the checkbox appears by
4876 // default.
4877 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
4878 EXPECT_EQ(security_interstitials::CMD_TEXT_FOUND,
4879 IsExtendedReportingCheckboxVisibleOnInterstitial());
4880
estark86642d602015-04-09 20:39:164881 // Set the enterprise policy to disallow opt-in.
4882 const PrefService* const prefs = browser()->profile()->GetPrefs();
4883 EXPECT_TRUE(
4884 prefs->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed));
4885 PolicyMap policies;
4886 policies.Set(key::kSafeBrowsingExtendedReportingOptInAllowed,
fhorschig64834b712015-09-21 14:20:234887 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:194888 base::WrapUnique(new base::Value(false)), nullptr);
estark86642d602015-04-09 20:39:164889 UpdateProviderPolicy(policies);
4890 EXPECT_FALSE(
4891 prefs->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed));
4892
Luke Zielinski389909fa2018-06-10 02:10:564893 // Navigate to an SSL error page, the checkbox should not appear.
estark86642d602015-04-09 20:39:164894 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
Luke Zielinski389909fa2018-06-10 02:10:564895 EXPECT_EQ(security_interstitials::CMD_TEXT_NOT_FOUND,
4896 IsExtendedReportingCheckboxVisibleOnInterstitial());
estark86642d602015-04-09 20:39:164897}
4898
Luke Zielinski47a92852018-03-01 20:42:574899// Test that when extended reporting is managed by policy, the opt-in checkbox
4900// does not appear on SSL blocking pages.
Carlos IL5a9e7512019-06-13 22:35:284901IN_PROC_BROWSER_TEST_F(PolicyTest, SafeBrowsingExtendedReportingPolicyManaged) {
Luke Zielinski47a92852018-03-01 20:42:574902 net::EmbeddedTestServer https_server_expired(
4903 net::EmbeddedTestServer::TYPE_HTTPS);
4904 https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
4905 https_server_expired.ServeFilesFromSourceDirectory("chrome/test/data");
4906 ASSERT_TRUE(https_server_expired.Start());
4907
Luke Zielinski389909fa2018-06-10 02:10:564908 // Set the extended reporting pref to True and ensure the enterprise policy
4909 // can overwrite it.
4910 PrefService* prefs = browser()->profile()->GetPrefs();
4911 prefs->SetBoolean(prefs::kSafeBrowsingScoutReportingEnabled, true);
4912
4913 // First, navigate to an SSL error page and make sure the checkbox appears by
4914 // default.
4915 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
4916 EXPECT_EQ(security_interstitials::CMD_TEXT_FOUND,
4917 IsExtendedReportingCheckboxVisibleOnInterstitial());
4918
Luke Zielinski47a92852018-03-01 20:42:574919 // Set the enterprise policy to disable extended reporting.
Luke Zielinski47a92852018-03-01 20:42:574920 EXPECT_TRUE(
4921 prefs->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed));
4922 PolicyMap policies;
4923 policies.Set(key::kSafeBrowsingExtendedReportingEnabled,
4924 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
4925 base::WrapUnique(new base::Value(false)), nullptr);
4926 UpdateProviderPolicy(policies);
Luke Zielinski389909fa2018-06-10 02:10:564927 // Policy should have overwritten the pref, and it should be managed.
4928 EXPECT_FALSE(prefs->GetBoolean(prefs::kSafeBrowsingScoutReportingEnabled));
4929 EXPECT_TRUE(
4930 prefs->IsManagedPreference(prefs::kSafeBrowsingScoutReportingEnabled));
4931
4932 // Also make sure the SafeBrowsing prefs helper functions agree with the
4933 // policy.
Luke Zielinski47a92852018-03-01 20:42:574934 EXPECT_TRUE(safe_browsing::IsExtendedReportingPolicyManaged(*prefs));
4935 // Note that making SBER policy managed does NOT affect the SBEROptInAllowed
4936 // setting, which is intentionally kept distinct for now. When the latter is
4937 // deprecated, then SBER's policy management will imply whether the checkbox
4938 // is visible.
4939 EXPECT_TRUE(safe_browsing::IsExtendedReportingOptInAllowed(*prefs));
4940
Luke Zielinski389909fa2018-06-10 02:10:564941 // Navigate to an SSL error page, the checkbox should not appear.
Luke Zielinski47a92852018-03-01 20:42:574942 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
Luke Zielinski389909fa2018-06-10 02:10:564943 EXPECT_EQ(security_interstitials::CMD_TEXT_NOT_FOUND,
4944 IsExtendedReportingCheckboxVisibleOnInterstitial());
Luke Zielinski47a92852018-03-01 20:42:574945}
4946
fahle66e7ff2015-04-23 19:38:304947// Test that when SSL error overriding is allowed by policy (default), the
4948// proceed link appears on SSL blocking pages.
Carlos IL5a9e7512019-06-13 22:35:284949IN_PROC_BROWSER_TEST_F(PolicyTest, SSLErrorOverridingAllowed) {
svaldeza01f7d92015-11-18 17:47:564950 net::EmbeddedTestServer https_server_expired(
4951 net::EmbeddedTestServer::TYPE_HTTPS);
4952 https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
4953 https_server_expired.ServeFilesFromSourceDirectory("chrome/test/data");
fahle66e7ff2015-04-23 19:38:304954 ASSERT_TRUE(https_server_expired.Start());
4955
4956 const PrefService* const prefs = browser()->profile()->GetPrefs();
4957
4958 // Policy should allow overriding by default.
4959 EXPECT_TRUE(prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed));
4960
4961 // Policy allows overriding - navigate to an SSL error page and expect the
4962 // proceed link.
4963 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
Carlos IL0ea4e592018-05-11 01:51:574964 content::WebContents* tab =
4965 browser()->tab_strip_model()->GetActiveWebContents();
4966 WaitForInterstitial(tab);
fahle66e7ff2015-04-23 19:38:304967
4968 // The interstitial should display the proceed link.
4969 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
Carlos IL5a9e7512019-06-13 22:35:284970 tab->GetMainFrame(), "proceed-link"));
fahle66e7ff2015-04-23 19:38:304971}
4972
4973// Test that when SSL error overriding is disallowed by policy, the
felt2d3f65e2015-05-18 15:26:044974// proceed link does not appear on SSL blocking pages and users should not
4975// be able to proceed.
Carlos IL5a9e7512019-06-13 22:35:284976IN_PROC_BROWSER_TEST_F(PolicyTest, SSLErrorOverridingDisallowed) {
svaldeza01f7d92015-11-18 17:47:564977 net::EmbeddedTestServer https_server_expired(
4978 net::EmbeddedTestServer::TYPE_HTTPS);
4979 https_server_expired.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
4980 https_server_expired.ServeFilesFromSourceDirectory("chrome/test/data");
fahle66e7ff2015-04-23 19:38:304981 ASSERT_TRUE(https_server_expired.Start());
4982
4983 const PrefService* const prefs = browser()->profile()->GetPrefs();
4984 EXPECT_TRUE(prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed));
4985
4986 // Disallowing the proceed link by setting the policy to |false|.
4987 PolicyMap policies;
4988 policies.Set(key::kSSLErrorOverrideAllowed, POLICY_LEVEL_MANDATORY,
fhorschig64834b712015-09-21 14:20:234989 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:194990 base::WrapUnique(new base::Value(false)), nullptr);
fahle66e7ff2015-04-23 19:38:304991 UpdateProviderPolicy(policies);
4992
4993 // Policy should not allow overriding anymore.
4994 EXPECT_FALSE(prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed));
4995
4996 // Policy disallows overriding - navigate to an SSL error page and expect no
4997 // proceed link.
4998 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
Carlos IL0ea4e592018-05-11 01:51:574999 content::WebContents* tab =
5000 browser()->tab_strip_model()->GetActiveWebContents();
5001 WaitForInterstitial(tab);
fahle66e7ff2015-04-23 19:38:305002
5003 // The interstitial should not display the proceed link.
5004 EXPECT_FALSE(chrome_browser_interstitials::IsInterstitialDisplayingText(
Carlos IL5a9e7512019-06-13 22:35:285005 tab->GetMainFrame(), "proceed-link"));
felt2d3f65e2015-05-18 15:26:045006
5007 // The interstitial should not proceed, even if the command is sent in
5008 // some other way (e.g., via the keyboard shortcut).
Carlos IL0ea4e592018-05-11 01:51:575009 SendInterstitialCommand(tab, security_interstitials::CMD_PROCEED);
5010 EXPECT_TRUE(IsShowingInterstitial(tab));
fahle66e7ff2015-04-23 19:38:305011}
5012
afakhry174069722016-05-24 19:16:165013// Test that TaskManagerInterface::IsEndProcessEnabled is controlled by
hunyadyme7a32292016-04-20 00:23:435014// TaskManagerEndProcessEnabled policy
5015IN_PROC_BROWSER_TEST_F(PolicyTest, TaskManagerEndProcessEnabled) {
5016 // By default it's allowed to end tasks.
avi24d693f2016-08-06 18:03:525017 EXPECT_TRUE(task_manager::TaskManagerInterface::IsEndProcessEnabled());
hunyadyme7a32292016-04-20 00:23:435018
5019 // Disabling ending tasks in task manager by policy
5020 PolicyMap policies1;
5021 policies1.Set(key::kTaskManagerEndProcessEnabled, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:095022 POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:195023 base::WrapUnique(new base::Value(false)), nullptr);
hunyadyme7a32292016-04-20 00:23:435024 UpdateProviderPolicy(policies1);
5025
5026 // Policy should not allow ending tasks anymore.
avi24d693f2016-08-06 18:03:525027 EXPECT_FALSE(task_manager::TaskManagerInterface::IsEndProcessEnabled());
hunyadyme7a32292016-04-20 00:23:435028
5029 // Enabling ending tasks in task manager by policy
5030 PolicyMap policies2;
5031 policies2.Set(key::kTaskManagerEndProcessEnabled, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:095032 POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:195033 base::WrapUnique(new base::Value(true)), nullptr);
hunyadyme7a32292016-04-20 00:23:435034 UpdateProviderPolicy(policies2);
5035
5036 // Policy should allow ending tasks again.
avi24d693f2016-08-06 18:03:525037 EXPECT_TRUE(task_manager::TaskManagerInterface::IsEndProcessEnabled());
hunyadyme7a32292016-04-20 00:23:435038}
5039
Jialiu Lin4d7c6042018-04-04 17:45:355040// Test that when password protection warning trigger is set for users who are
5041// not signed-into Chrome, Chrome password protection service gets the correct
5042// value.
5043IN_PROC_BROWSER_TEST_F(PolicyTest,
5044 PasswordProtectionWarningTriggerNotLoggedIn) {
5045 MockPasswordProtectionService mock_service(
5046 g_browser_process->safe_browsing_service(), browser()->profile());
Jialiu Lin4d7c6042018-04-04 17:45:355047
Jialiu Lin1d1a55e2018-05-18 17:40:155048 // If user is not signed-in, |GetPasswordProtectionWarningTriggerPref(...)|
Bettina06c32372019-04-16 16:53:555049 // should return |PHISHING_REUSE| unless specified by policy.
Jialiu Lin4d7c6042018-04-04 17:45:355050 EXPECT_CALL(mock_service, GetSyncAccountType())
5051 .WillRepeatedly(Return(safe_browsing::LoginReputationClientRequest::
5052 PasswordReuseEvent::NOT_SIGNED_IN));
Jialiu Lin219b97862018-01-27 02:39:595053 const PrefService* const prefs = browser()->profile()->GetPrefs();
Jialiu Lin219b97862018-01-27 02:39:595054 EXPECT_FALSE(prefs->FindPreference(prefs::kPasswordProtectionWarningTrigger)
5055 ->IsManaged());
Bettina06c32372019-04-16 16:53:555056 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155057 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin219b97862018-01-27 02:39:595058 // Sets the enterprise policy to 1 (a.k.a PASSWORD_REUSE).
5059 PolicyMap policies;
5060 policies.Set(key::kPasswordProtectionWarningTrigger, POLICY_LEVEL_MANDATORY,
5061 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jialiu Lin4d7c6042018-04-04 17:45:355062 std::make_unique<base::Value>(1), nullptr);
5063 UpdateProviderPolicy(policies);
5064 EXPECT_TRUE(prefs->FindPreference(prefs::kPasswordProtectionWarningTrigger)
5065 ->IsManaged());
Jialiu Lin49602f042018-06-14 19:50:065066 EXPECT_EQ(safe_browsing::PASSWORD_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155067 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin4d7c6042018-04-04 17:45:355068 // Sets the enterprise policy to 2 (a.k.a PHISHING_REUSE).
5069 policies.Set(key::kPasswordProtectionWarningTrigger, POLICY_LEVEL_MANDATORY,
5070 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5071 std::make_unique<base::Value>(2), nullptr);
5072 UpdateProviderPolicy(policies);
Jialiu Lin49602f042018-06-14 19:50:065073 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155074 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin4d7c6042018-04-04 17:45:355075}
5076
5077// Test that when password protection warning trigger is set for Gmail users,
5078// Chrome password protection service gets the correct
5079// value.
5080IN_PROC_BROWSER_TEST_F(PolicyTest, PasswordProtectionWarningTriggerGmail) {
5081 MockPasswordProtectionService mock_service(
5082 g_browser_process->safe_browsing_service(), browser()->profile());
Jialiu Lin4d7c6042018-04-04 17:45:355083
Jialiu Lin1d1a55e2018-05-18 17:40:155084 // If user is a Gmail user, |GetPasswordProtectionWarningTriggerPref(...)|
5085 // should return |PHISHING_REUSE| unless specified by policy.
Jialiu Lin4d7c6042018-04-04 17:45:355086 EXPECT_CALL(mock_service, GetSyncAccountType())
5087 .WillRepeatedly(Return(safe_browsing::LoginReputationClientRequest::
5088 PasswordReuseEvent::GMAIL));
5089 const PrefService* const prefs = browser()->profile()->GetPrefs();
5090 EXPECT_FALSE(prefs->FindPreference(prefs::kPasswordProtectionWarningTrigger)
5091 ->IsManaged());
5092 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155093 mock_service.GetPasswordProtectionWarningTriggerPref());
Bettina06c32372019-04-16 16:53:555094 // Sets the enterprise policy to 1 (a.k.a PASSWORD_REUSE). Gmail accounts
5095 // should always return PHISHING_REUSE regardless of what the policy is set
5096 // to.
Jialiu Lin4d7c6042018-04-04 17:45:355097 PolicyMap policies;
5098 policies.Set(key::kPasswordProtectionWarningTrigger, POLICY_LEVEL_MANDATORY,
5099 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5100 std::make_unique<base::Value>(1), nullptr);
Jialiu Lin219b97862018-01-27 02:39:595101 UpdateProviderPolicy(policies);
5102 EXPECT_TRUE(prefs->FindPreference(prefs::kPasswordProtectionWarningTrigger)
5103 ->IsManaged());
Bettina06c32372019-04-16 16:53:555104 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155105 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin219b97862018-01-27 02:39:595106 // Sets the enterprise policy to 2 (a.k.a PHISHING_REUSE).
5107 policies.Set(key::kPasswordProtectionWarningTrigger, POLICY_LEVEL_MANDATORY,
5108 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jialiu Lin4d7c6042018-04-04 17:45:355109 std::make_unique<base::Value>(2), nullptr);
Jialiu Lin219b97862018-01-27 02:39:595110 UpdateProviderPolicy(policies);
5111 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155112 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin219b97862018-01-27 02:39:595113}
5114
Jialiu Lin4d7c6042018-04-04 17:45:355115// Test that when password protection warning trigger is set for GSuite users,
5116// Chrome password protection service gets the correct value.
5117IN_PROC_BROWSER_TEST_F(PolicyTest, PasswordProtectionWarningTriggerGSuite) {
5118 MockPasswordProtectionService mock_service(
5119 g_browser_process->safe_browsing_service(), browser()->profile());
5120 EXPECT_CALL(mock_service, GetSyncAccountType())
5121 .WillRepeatedly(Return(safe_browsing::LoginReputationClientRequest::
5122 PasswordReuseEvent::GSUITE));
Jialiu Lin92b357f2018-04-24 17:08:455123 const PrefService* const prefs = browser()->profile()->GetPrefs();
Jialiu Lin4d7c6042018-04-04 17:45:355124 PolicyMap policies;
5125
Jialiu Lin1d1a55e2018-05-18 17:40:155126 // If user is a GSuite user, |GetPasswordProtectionWarningTriggerPref(...)|
Bettina06c32372019-04-16 16:53:555127 // should return |PHISHING_REUSE| unless specified by policy.
Jialiu Lin92b357f2018-04-24 17:08:455128 EXPECT_FALSE(prefs->FindPreference(prefs::kPasswordProtectionWarningTrigger)
5129 ->IsManaged());
Bettina06c32372019-04-16 16:53:555130 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155131 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin92b357f2018-04-24 17:08:455132 // Sets the enterprise policy to 1 (a.k.a PASSWORD_REUSE).
Jialiu Lin4d7c6042018-04-04 17:45:355133 policies.Set(key::kPasswordProtectionWarningTrigger, POLICY_LEVEL_MANDATORY,
5134 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5135 std::make_unique<base::Value>(1), nullptr);
5136 UpdateProviderPolicy(policies);
Jialiu Lin92b357f2018-04-24 17:08:455137 EXPECT_TRUE(prefs->FindPreference(prefs::kPasswordProtectionWarningTrigger)
5138 ->IsManaged());
Jialiu Lin4d7c6042018-04-04 17:45:355139 EXPECT_EQ(safe_browsing::PASSWORD_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155140 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin92b357f2018-04-24 17:08:455141 // Sets the enterprise policy to 2 (a.k.a PHISHING_REUSE).
Jialiu Lin4d7c6042018-04-04 17:45:355142 policies.Set(key::kPasswordProtectionWarningTrigger, POLICY_LEVEL_MANDATORY,
5143 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5144 std::make_unique<base::Value>(2), nullptr);
5145 UpdateProviderPolicy(policies);
5146 EXPECT_EQ(safe_browsing::PHISHING_REUSE,
Jialiu Lin1d1a55e2018-05-18 17:40:155147 mock_service.GetPasswordProtectionWarningTriggerPref());
Jialiu Lin219b97862018-01-27 02:39:595148}
5149
Jialiu Lin924ee4d2018-02-13 20:34:405150// Test that when safe browsing whitelist domains are set by policy, safe
5151// browsing service gets the correct value.
5152IN_PROC_BROWSER_TEST_F(PolicyTest, SafeBrowsingWhitelistDomains) {
5153 // Without setting up the enterprise policy,
5154 // |GetSafeBrowsingDomainsPref(..) should return empty list.
5155 const PrefService* const prefs = browser()->profile()->GetPrefs();
5156 EXPECT_FALSE(
5157 prefs->FindPreference(prefs::kSafeBrowsingWhitelistDomains)->IsManaged());
5158 std::vector<std::string> canonicalized_domains;
5159 safe_browsing::GetSafeBrowsingWhitelistDomainsPref(*prefs,
5160 &canonicalized_domains);
5161 EXPECT_TRUE(canonicalized_domains.empty());
5162
5163 // Add 2 whitelisted domains to this policy.
5164 PolicyMap policies;
5165 base::ListValue whitelist_domains;
5166 whitelist_domains.AppendString("mydomain.com");
5167 whitelist_domains.AppendString("mydomain.net");
5168 policies.Set(key::kSafeBrowsingWhitelistDomains, POLICY_LEVEL_MANDATORY,
5169 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5170 whitelist_domains.CreateDeepCopy(), nullptr);
5171 UpdateProviderPolicy(policies);
5172 EXPECT_TRUE(
5173 prefs->FindPreference(prefs::kSafeBrowsingWhitelistDomains)->IsManaged());
5174 safe_browsing::GetSafeBrowsingWhitelistDomainsPref(*prefs,
5175 &canonicalized_domains);
5176 EXPECT_EQ(2u, canonicalized_domains.size());
5177 EXPECT_EQ("mydomain.com", canonicalized_domains[0]);
5178 EXPECT_EQ("mydomain.net", canonicalized_domains[1]);
5179
5180 // Invalid domains will be skipped.
5181 whitelist_domains.Clear();
5182 whitelist_domains.AppendString(std::string("%EF%BF%BDzyx.com"));
5183 policies.Set(key::kSafeBrowsingWhitelistDomains, POLICY_LEVEL_MANDATORY,
5184 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5185 whitelist_domains.CreateDeepCopy(), nullptr);
5186 UpdateProviderPolicy(policies);
5187 EXPECT_TRUE(
5188 prefs->FindPreference(prefs::kSafeBrowsingWhitelistDomains)->IsManaged());
5189 canonicalized_domains.clear();
5190 safe_browsing::GetSafeBrowsingWhitelistDomainsPref(*prefs,
5191 &canonicalized_domains);
5192 EXPECT_TRUE(canonicalized_domains.empty());
5193}
5194
5195// Test that when password protection login URLs are set by policy, password
5196// protection service gets the correct value.
5197IN_PROC_BROWSER_TEST_F(PolicyTest, PasswordProtectionLoginURLs) {
5198 // Without setting up the enterprise policy,
5199 // |GetPasswordProtectionLoginURLsPref(..) should return empty list.
5200 const PrefService* const prefs = browser()->profile()->GetPrefs();
Jialiu Lin924ee4d2018-02-13 20:34:405201 EXPECT_FALSE(
5202 prefs->FindPreference(prefs::kPasswordProtectionLoginURLs)->IsManaged());
5203 std::vector<GURL> login_urls;
Jialiu Linc534b0d2018-03-01 16:51:525204 safe_browsing::GetPasswordProtectionLoginURLsPref(*prefs, &login_urls);
Jialiu Lin924ee4d2018-02-13 20:34:405205 EXPECT_TRUE(login_urls.empty());
5206
5207 // Add 2 login URLs to this enterprise policy .
5208 PolicyMap policies;
5209 base::ListValue login_url_values;
5210 login_url_values.AppendString("https://login.mydomain.com");
5211 login_url_values.AppendString("https://mydomian.com/login.html");
5212 policies.Set(key::kPasswordProtectionLoginURLs, POLICY_LEVEL_MANDATORY,
5213 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5214 login_url_values.CreateDeepCopy(), nullptr);
5215 UpdateProviderPolicy(policies);
5216 EXPECT_TRUE(
5217 prefs->FindPreference(prefs::kPasswordProtectionLoginURLs)->IsManaged());
Jialiu Linc534b0d2018-03-01 16:51:525218 safe_browsing::GetPasswordProtectionLoginURLsPref(*prefs, &login_urls);
Jialiu Lin924ee4d2018-02-13 20:34:405219 EXPECT_EQ(2u, login_urls.size());
5220 EXPECT_EQ(GURL("https://login.mydomain.com"), login_urls[0]);
5221 EXPECT_EQ(GURL("https://mydomian.com/login.html"), login_urls[1]);
5222
5223 // Verify non-http/https schemes, or invalid URLs will be skipped.
5224 login_url_values.Clear();
5225 login_url_values.AppendString(std::string("invalid"));
5226 login_url_values.AppendString(std::string("ftp://login.mydomain.com"));
5227 policies.Set(key::kPasswordProtectionLoginURLs, POLICY_LEVEL_MANDATORY,
5228 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5229 login_url_values.CreateDeepCopy(), nullptr);
5230 UpdateProviderPolicy(policies);
5231 EXPECT_TRUE(
5232 prefs->FindPreference(prefs::kPasswordProtectionLoginURLs)->IsManaged());
5233 login_urls.clear();
Jialiu Linc534b0d2018-03-01 16:51:525234 safe_browsing::GetPasswordProtectionLoginURLsPref(*prefs, &login_urls);
Jialiu Lin924ee4d2018-02-13 20:34:405235 EXPECT_TRUE(login_urls.empty());
5236}
5237
5238// Test that when password protection change password URL is set by policy,
5239// password protection service gets the correct value.
5240IN_PROC_BROWSER_TEST_F(PolicyTest, PasswordProtectionChangePasswordURL) {
5241 // Without setting up the enterprise policy,
Jialiu Lin49602f042018-06-14 19:50:065242 // |GetEnterpriseChangePasswordURL(..) should return default GAIA change
5243 // password URL.
Jialiu Lin924ee4d2018-02-13 20:34:405244 const PrefService* const prefs = browser()->profile()->GetPrefs();
5245 const safe_browsing::ChromePasswordProtectionService* const service =
5246 safe_browsing::ChromePasswordProtectionService::
5247 GetPasswordProtectionService(browser()->profile());
5248 EXPECT_FALSE(
5249 prefs->FindPreference(prefs::kPasswordProtectionChangePasswordURL)
5250 ->IsManaged());
5251 EXPECT_FALSE(prefs->HasPrefPath(prefs::kPasswordProtectionChangePasswordURL));
Jialiu Lin49602f042018-06-14 19:50:065252 EXPECT_TRUE(service->GetEnterpriseChangePasswordURL().DomainIs(
5253 "accounts.google.com"));
Jialiu Lin924ee4d2018-02-13 20:34:405254
5255 // Add change password URL to this enterprise policy .
5256 PolicyMap policies;
5257 policies.Set(
5258 key::kPasswordProtectionChangePasswordURL, POLICY_LEVEL_MANDATORY,
5259 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5260 base::WrapUnique(new base::Value("https://changepassword.mydomain.com")),
5261 nullptr);
5262 UpdateProviderPolicy(policies);
5263 EXPECT_TRUE(prefs->FindPreference(prefs::kPasswordProtectionChangePasswordURL)
5264 ->IsManaged());
5265 EXPECT_EQ(GURL("https://changepassword.mydomain.com"),
Jialiu Lin49602f042018-06-14 19:50:065266 service->GetEnterpriseChangePasswordURL());
Jialiu Lin924ee4d2018-02-13 20:34:405267
5268 // Verify non-http/https change password URL will be skipped.
5269 policies.Set(key::kPasswordProtectionChangePasswordURL,
5270 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5271 base::WrapUnique(new base::Value("data:text/html,login page")),
5272 nullptr);
5273 UpdateProviderPolicy(policies);
5274 EXPECT_TRUE(prefs->FindPreference(prefs::kPasswordProtectionChangePasswordURL)
5275 ->IsManaged());
Jialiu Lin49602f042018-06-14 19:50:065276 EXPECT_TRUE(service->GetEnterpriseChangePasswordURL().DomainIs(
5277 "accounts.google.com"));
Jialiu Lin924ee4d2018-02-13 20:34:405278}
5279
imchengc2b6c182016-06-07 21:31:165280// Sets the proper policy before the browser is started.
5281template<bool enable>
5282class MediaRouterPolicyTest : public PolicyTest {
5283 public:
5284 void SetUpInProcessBrowserTestFixture() override {
5285 PolicyTest::SetUpInProcessBrowserTestFixture();
5286 PolicyMap policies;
5287 policies.Set(key::kEnableMediaRouter, POLICY_LEVEL_MANDATORY,
5288 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:305289 std::make_unique<base::Value>(enable), nullptr);
imchengc2b6c182016-06-07 21:31:165290 provider_.UpdateChromePolicy(policies);
5291 }
5292};
5293
5294using MediaRouterEnabledPolicyTest = MediaRouterPolicyTest<true>;
5295using MediaRouterDisabledPolicyTest = MediaRouterPolicyTest<false>;
5296
5297IN_PROC_BROWSER_TEST_F(MediaRouterEnabledPolicyTest, MediaRouterEnabled) {
5298 EXPECT_TRUE(media_router::MediaRouterEnabled(browser()->profile()));
5299}
5300
5301IN_PROC_BROWSER_TEST_F(MediaRouterDisabledPolicyTest, MediaRouterDisabled) {
5302 EXPECT_FALSE(media_router::MediaRouterEnabled(browser()->profile()));
5303}
takumif1a5f2852017-01-31 19:10:505304
Derek Cheng34478382018-04-07 00:32:595305#if !defined(OS_ANDROID)
takumif1a5f2852017-01-31 19:10:505306template <bool enable>
5307class MediaRouterActionPolicyTest : public PolicyTest {
5308 public:
5309 void SetUpInProcessBrowserTestFixture() override {
5310 PolicyTest::SetUpInProcessBrowserTestFixture();
5311 PolicyMap policies;
5312 policies.Set(key::kShowCastIconInToolbar, POLICY_LEVEL_MANDATORY,
5313 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:305314 std::make_unique<base::Value>(enable), nullptr);
takumif1a5f2852017-01-31 19:10:505315 provider_.UpdateChromePolicy(policies);
5316 }
takumif1a5f2852017-01-31 19:10:505317};
5318
5319using MediaRouterActionEnabledPolicyTest = MediaRouterActionPolicyTest<true>;
5320using MediaRouterActionDisabledPolicyTest = MediaRouterActionPolicyTest<false>;
5321
5322IN_PROC_BROWSER_TEST_F(MediaRouterActionEnabledPolicyTest,
5323 MediaRouterActionEnabled) {
5324 EXPECT_TRUE(
5325 MediaRouterActionController::IsActionShownByPolicy(browser()->profile()));
takumif1a5f2852017-01-31 19:10:505326}
5327
5328IN_PROC_BROWSER_TEST_F(MediaRouterActionDisabledPolicyTest,
5329 MediaRouterActionDisabled) {
5330 EXPECT_FALSE(
5331 MediaRouterActionController::IsActionShownByPolicy(browser()->profile()));
takumif1a5f2852017-01-31 19:10:505332}
imchengc2b6c182016-06-07 21:31:165333
Derek Cheng34478382018-04-07 00:32:595334class MediaRouterCastAllowAllIPsPolicyTest
5335 : public PolicyTest,
5336 public testing::WithParamInterface<bool> {
5337 public:
5338 void SetUpInProcessBrowserTestFixture() override {
5339 PolicyTest::SetUpInProcessBrowserTestFixture();
5340 PolicyMap policies;
5341 policies.Set(key::kMediaRouterCastAllowAllIPs, POLICY_LEVEL_MANDATORY,
5342 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5343 std::make_unique<base::Value>(is_enabled()), nullptr);
5344 provider_.UpdateChromePolicy(policies);
5345 }
5346
5347 bool is_enabled() const { return GetParam(); }
5348};
5349
5350IN_PROC_BROWSER_TEST_P(MediaRouterCastAllowAllIPsPolicyTest, RunTest) {
5351 PrefService* const pref = g_browser_process->local_state();
5352 ASSERT_TRUE(pref);
5353 EXPECT_EQ(is_enabled(),
5354 pref->GetBoolean(media_router::prefs::kMediaRouterCastAllowAllIPs));
5355 EXPECT_TRUE(pref->IsManagedPreference(
5356 media_router::prefs::kMediaRouterCastAllowAllIPs));
5357 EXPECT_EQ(is_enabled(), media_router::GetCastAllowAllIPsPref(pref));
5358}
5359
Victor Costane5e91512019-02-13 08:24:025360INSTANTIATE_TEST_SUITE_P(MediaRouterCastAllowAllIPsPolicyTestInstance,
5361 MediaRouterCastAllowAllIPsPolicyTest,
5362 testing::Values(true, false));
Derek Cheng34478382018-04-07 00:32:595363#endif // !defined(OS_ANDROID)
5364
guidouca055a542016-08-11 11:15:535365// Sets the proper policy before the browser is started.
5366template <bool enable>
5367class WebRtcUdpPortRangePolicyTest : public PolicyTest {
5368 public:
5369 WebRtcUdpPortRangePolicyTest() = default;
5370 void SetUpInProcessBrowserTestFixture() override {
5371 PolicyTest::SetUpInProcessBrowserTestFixture();
5372 PolicyMap policies;
5373 if (enable) {
ricea86fa1dd2016-09-13 05:59:455374 policies.Set(key::kWebRtcUdpPortRange, POLICY_LEVEL_MANDATORY,
5375 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:305376 std::make_unique<base::Value>(kTestWebRtcUdpPortRange),
ricea86fa1dd2016-09-13 05:59:455377 nullptr);
guidouca055a542016-08-11 11:15:535378 }
5379 provider_.UpdateChromePolicy(policies);
5380 }
5381
5382 private:
5383 DISALLOW_COPY_AND_ASSIGN(WebRtcUdpPortRangePolicyTest<enable>);
5384};
5385
5386using WebRtcUdpPortRangeEnabledPolicyTest = WebRtcUdpPortRangePolicyTest<true>;
5387using WebRtcUdpPortRangeDisabledPolicyTest =
5388 WebRtcUdpPortRangePolicyTest<false>;
5389
5390IN_PROC_BROWSER_TEST_F(WebRtcUdpPortRangeEnabledPolicyTest,
5391 WebRtcUdpPortRangeEnabled) {
5392 std::string port_range;
5393 const PrefService::Preference* pref =
5394 user_prefs::UserPrefs::Get(browser()->profile())
5395 ->FindPreference(prefs::kWebRTCUDPPortRange);
5396 pref->GetValue()->GetAsString(&port_range);
5397 EXPECT_EQ(kTestWebRtcUdpPortRange, port_range);
5398}
5399
5400IN_PROC_BROWSER_TEST_F(WebRtcUdpPortRangeDisabledPolicyTest,
5401 WebRtcUdpPortRangeDisabled) {
5402 std::string port_range;
5403 const PrefService::Preference* pref =
5404 user_prefs::UserPrefs::Get(browser()->profile())
5405 ->FindPreference(prefs::kWebRTCUDPPortRange);
5406 pref->GetValue()->GetAsString(&port_range);
5407 EXPECT_TRUE(port_range.empty());
5408}
guidouca055a542016-08-11 11:15:535409
sorin0b99b8d2016-08-22 20:40:535410// Tests the ComponentUpdater's EnabledComponentUpdates group policy by
5411// calling the OnDemand interface. It uses the network interceptor to inspect
5412// the presence of the updatedisabled="true" attribute in the update check
5413// request. The update check request is expected to fail, since CUP fails.
5414class ComponentUpdaterPolicyTest : public PolicyTest {
5415 public:
5416 ComponentUpdaterPolicyTest();
5417 ~ComponentUpdaterPolicyTest() override;
5418
Antonio Gomesb6162502018-06-28 20:21:555419 void SetUpCommandLine(base::CommandLine* command_line) override;
5420 void SetUpOnMainThread() override;
5421
sorin0b99b8d2016-08-22 20:40:535422 protected:
5423 using TestCaseAction = void (ComponentUpdaterPolicyTest::*)();
5424 using TestCase = std::pair<TestCaseAction, TestCaseAction>;
5425
5426 // These test scenarios run as part of one test case by using the
5427 // CallAsync helper, which calls OnDemand, then chains up to the next
5428 // scenario when the OnDemandComplete callback fires.
5429 void DefaultPolicy_GroupPolicySupported();
5430 void FinishDefaultPolicy_GroupPolicySupported();
5431
5432 void DefaultPolicy_GroupPolicyNotSupported();
5433 void FinishDefaultPolicy_GroupPolicyNotSupported();
5434
5435 void EnabledPolicy_GroupPolicySupported();
5436 void FinishEnabledPolicy_GroupPolicySupported();
5437
5438 void EnabledPolicy_GroupPolicyNotSupported();
5439 void FinishEnabledPolicy_GroupPolicyNotSupported();
5440
5441 void DisabledPolicy_GroupPolicySupported();
5442 void FinishDisabled_PolicyGroupPolicySupported();
5443
5444 void DisabledPolicy_GroupPolicyNotSupported();
5445 void FinishDisabledPolicy_GroupPolicyNotSupported();
5446
5447 void BeginTest();
5448 void EndTest();
5449
5450 void UpdateComponent(const update_client::CrxComponent& crx_component);
5451 void CallAsync(TestCaseAction action);
5452 void VerifyExpectations(bool update_disabled);
5453
5454 void SetEnableComponentUpdates(bool enable_component_updates);
5455
5456 static update_client::CrxComponent MakeCrxComponent(
5457 bool supports_group_policy_enable_component_updates);
5458
5459 TestCase cur_test_case_;
5460
5461 static const char component_id_[];
5462
5463 static const bool kUpdateDisabled = true;
5464
5465 private:
sorin7b8650522016-11-02 18:23:415466 void OnDemandComplete(update_client::Error error);
sorin0b99b8d2016-08-22 20:40:535467
Antonio Gomesb6162502018-06-28 20:21:555468 std::unique_ptr<update_client::URLLoaderPostInterceptor> post_interceptor_;
sorin0b99b8d2016-08-22 20:40:535469
5470 // This member is owned by g_browser_process;
Sorin Jianu015681f2018-04-04 16:43:335471 component_updater::ComponentUpdateService* cus_ = nullptr;
sorin0b99b8d2016-08-22 20:40:535472
Antonio Gomesb6162502018-06-28 20:21:555473 net::EmbeddedTestServer https_server_;
5474
sorin0b99b8d2016-08-22 20:40:535475 DISALLOW_COPY_AND_ASSIGN(ComponentUpdaterPolicyTest);
5476};
5477
5478const char ComponentUpdaterPolicyTest::component_id_[] =
5479 "jebgalgnebhfojomionfpkfelancnnkf";
5480
Antonio Gomesb6162502018-06-28 20:21:555481ComponentUpdaterPolicyTest::ComponentUpdaterPolicyTest()
5482 : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
sorin0b99b8d2016-08-22 20:40:535483
5484ComponentUpdaterPolicyTest::~ComponentUpdaterPolicyTest() {}
5485
Antonio Gomesb6162502018-06-28 20:21:555486void ComponentUpdaterPolicyTest::SetUpCommandLine(
5487 base::CommandLine* command_line) {
5488 // Set up the mock server, for the network requests.
5489 ASSERT_TRUE(https_server_.InitializeAndListen());
5490 const std::string val = base::StringPrintf(
5491 "url-source=%s", https_server_.GetURL("/service/update2").spec().c_str());
5492 command_line->AppendSwitchASCII(switches::kComponentUpdater, val.c_str());
5493 PolicyTest::SetUpCommandLine(command_line);
5494}
5495
5496void ComponentUpdaterPolicyTest::SetUpOnMainThread() {
5497 const auto config = component_updater::MakeChromeComponentUpdaterConfigurator(
5498 base::CommandLine::ForCurrentProcess(), g_browser_process->local_state());
5499 const auto urls = config->UpdateUrl();
5500 ASSERT_EQ(1u, urls.size());
5501 post_interceptor_ = std::make_unique<update_client::URLLoaderPostInterceptor>(
5502 urls, &https_server_);
5503
5504 https_server_.StartAcceptingConnections();
5505 PolicyTest::SetUpOnMainThread();
5506}
5507
sorin0b99b8d2016-08-22 20:40:535508void ComponentUpdaterPolicyTest::SetEnableComponentUpdates(
5509 bool enable_component_updates) {
5510 PolicyMap policies;
jdoerrie239723572017-03-02 12:09:195511 policies.Set(key::kComponentUpdatesEnabled, POLICY_LEVEL_MANDATORY,
5512 POLICY_SCOPE_MACHINE, POLICY_SOURCE_ENTERPRISE_DEFAULT,
5513 base::WrapUnique(new base::Value(enable_component_updates)),
5514 nullptr);
sorin0b99b8d2016-08-22 20:40:535515 UpdateProviderPolicy(policies);
5516}
5517
5518update_client::CrxComponent ComponentUpdaterPolicyTest::MakeCrxComponent(
5519 bool supports_group_policy_enable_component_updates) {
5520 class MockInstaller : public update_client::CrxInstaller {
5521 public:
5522 MockInstaller() {}
5523
Sorin Jianua8ef73d2017-11-02 16:55:175524 void Install(const base::FilePath& unpack_path,
5525 const std::string& public_key,
Daniel Cheng51249952018-04-27 06:48:505526 Callback callback) override {
Sorin Jianua8ef73d2017-11-02 16:55:175527 DoInstall(unpack_path, public_key, std::move(callback));
5528 }
5529
sorin0b99b8d2016-08-22 20:40:535530 MOCK_METHOD1(OnUpdateError, void(int error));
Sorin Jianua8ef73d2017-11-02 16:55:175531 MOCK_METHOD3(DoInstall,
Sorin Jianu7aa6d1f2017-10-13 20:29:295532 void(const base::FilePath& unpack_path,
Sorin Jianuea5534e92017-10-27 01:40:285533 const std::string& public_key,
Sorin Jianuf40ab4b32017-10-06 22:53:415534 const Callback& callback));
sorin0b99b8d2016-08-22 20:40:535535 MOCK_METHOD2(GetInstalledFile,
5536 bool(const std::string& file, base::FilePath* installed_file));
5537 MOCK_METHOD0(Uninstall, bool());
5538
5539 private:
5540 ~MockInstaller() override {}
5541 };
5542
5543 // component id "jebgalgnebhfojomionfpkfelancnnkf".
5544 static const uint8_t jebg_hash[] = {
5545 0x94, 0x16, 0x0b, 0x6d, 0x41, 0x75, 0xe9, 0xec, 0x8e, 0xd5, 0xfa,
5546 0x54, 0xb0, 0xd2, 0xdd, 0xa5, 0x6e, 0x05, 0x6b, 0xe8, 0x73, 0x47,
5547 0xf6, 0xc4, 0x11, 0x9f, 0xbc, 0xb3, 0x09, 0xb3, 0x5b, 0x40};
5548
5549 // The component uses HTTPS only for network interception purposes.
5550 update_client::CrxComponent crx_component;
5551 crx_component.pk_hash.assign(std::begin(jebg_hash), std::end(jebg_hash));
pwnall8c3feb22016-09-01 21:10:445552 crx_component.version = base::Version("0.9");
sorin0b99b8d2016-08-22 20:40:535553 crx_component.installer = scoped_refptr<MockInstaller>(new MockInstaller());
5554 crx_component.requires_network_encryption = true;
5555 crx_component.supports_group_policy_enable_component_updates =
5556 supports_group_policy_enable_component_updates;
5557
5558 return crx_component;
5559}
5560
5561void ComponentUpdaterPolicyTest::UpdateComponent(
5562 const update_client::CrxComponent& crx_component) {
5563 post_interceptor_->Reset();
5564 EXPECT_TRUE(post_interceptor_->ExpectRequest(
Sorin Jianu015681f2018-04-04 16:43:335565 std::make_unique<update_client::PartialMatch>("updatecheck")));
sorin0b99b8d2016-08-22 20:40:535566 EXPECT_TRUE(cus_->RegisterComponent(crx_component));
5567 cus_->GetOnDemandUpdater().OnDemandUpdate(
Sorin Jianud20ed8532018-06-28 17:24:315568 component_id_, component_updater::OnDemandUpdater::Priority::FOREGROUND,
5569 base::BindOnce(&ComponentUpdaterPolicyTest::OnDemandComplete,
5570 base::Unretained(this)));
sorin0b99b8d2016-08-22 20:40:535571}
5572
5573void ComponentUpdaterPolicyTest::CallAsync(TestCaseAction action) {
Eric Seckler8652dcd52018-09-20 10:42:285574 base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI},
5575 base::BindOnce(action, base::Unretained(this)));
sorin0b99b8d2016-08-22 20:40:535576}
5577
sorin7b8650522016-11-02 18:23:415578void ComponentUpdaterPolicyTest::OnDemandComplete(update_client::Error error) {
sorin0b99b8d2016-08-22 20:40:535579 CallAsync(cur_test_case_.second);
5580}
5581
5582void ComponentUpdaterPolicyTest::BeginTest() {
5583 cus_ = g_browser_process->component_updater();
5584
wafflesa4f53d42017-02-07 01:19:315585 const auto config = component_updater::MakeChromeComponentUpdaterConfigurator(
Sorin Jianu556147d2018-01-19 21:55:215586 base::CommandLine::ForCurrentProcess(), g_browser_process->local_state());
wafflesa4f53d42017-02-07 01:19:315587 const auto urls = config->UpdateUrl();
5588 ASSERT_TRUE(urls.size());
5589 const GURL url = urls.front();
5590
sorin0b99b8d2016-08-22 20:40:535591 cur_test_case_ = std::make_pair(
5592 &ComponentUpdaterPolicyTest::DefaultPolicy_GroupPolicySupported,
5593 &ComponentUpdaterPolicyTest::FinishDefaultPolicy_GroupPolicySupported);
5594
5595 CallAsync(cur_test_case_.first);
5596}
5597
5598void ComponentUpdaterPolicyTest::EndTest() {
Antonio Gomesb6162502018-06-28 20:21:555599 post_interceptor_.reset();
sorin0b99b8d2016-08-22 20:40:535600 cus_ = nullptr;
5601
Gabriel Charette53a9ef812017-07-26 12:36:235602 base::RunLoop::QuitCurrentWhenIdleDeprecated();
sorin0b99b8d2016-08-22 20:40:535603}
5604
5605void ComponentUpdaterPolicyTest::VerifyExpectations(bool update_disabled) {
5606 EXPECT_EQ(1, post_interceptor_->GetHitCount())
5607 << post_interceptor_->GetRequestsAsString();
5608 ASSERT_EQ(1, post_interceptor_->GetCount())
5609 << post_interceptor_->GetRequestsAsString();
Sorin Jianu55587d32018-11-14 21:43:275610
5611 const auto& request = post_interceptor_->GetRequestBody(0);
5612
5613 // Handle XML and JSON protocols.
5614 if (base::StartsWith(request, "<?xml", base::CompareCase::SENSITIVE)) {
5615 EXPECT_NE(std::string::npos,
5616 request.find(base::StringPrintf(
5617 "<updatecheck%s/>",
5618 update_disabled ? " updatedisabled=\"true\"" : "")));
5619 } else if (base::StartsWith(request, R"({"request":{)",
5620 base::CompareCase::SENSITIVE)) {
Lei Zhang025edc22019-02-16 05:02:255621 const auto root = base::JSONReader().ReadDeprecated(request);
Sorin Jianu55587d32018-11-14 21:43:275622 ASSERT_TRUE(root);
5623 const auto* update_check =
5624 root->FindKey("request")->FindKey("app")->GetList()[0].FindKey(
5625 "updatecheck");
5626 ASSERT_TRUE(update_check);
5627 if (update_disabled) {
5628 EXPECT_EQ(true, update_check->FindKey("updatedisabled")->GetBool());
5629 } else {
5630 EXPECT_FALSE(update_check->FindKey("updatedisabled"));
5631 }
5632 } else {
5633 NOTREACHED();
5634 }
sorin0b99b8d2016-08-22 20:40:535635}
5636
5637void ComponentUpdaterPolicyTest::DefaultPolicy_GroupPolicySupported() {
5638 UpdateComponent(MakeCrxComponent(true));
5639}
5640
5641void ComponentUpdaterPolicyTest::FinishDefaultPolicy_GroupPolicySupported() {
5642 // Default policy && policy support -> updates are enabled.
5643 VerifyExpectations(!kUpdateDisabled);
5644
5645 cur_test_case_ = std::make_pair(
5646 &ComponentUpdaterPolicyTest::DefaultPolicy_GroupPolicyNotSupported,
5647 &ComponentUpdaterPolicyTest::FinishDefaultPolicy_GroupPolicyNotSupported);
5648 CallAsync(cur_test_case_.first);
5649}
5650
5651void ComponentUpdaterPolicyTest::DefaultPolicy_GroupPolicyNotSupported() {
5652 UpdateComponent(MakeCrxComponent(false));
5653}
5654
5655void ComponentUpdaterPolicyTest::FinishDefaultPolicy_GroupPolicyNotSupported() {
5656 // Default policy && no policy support -> updates are enabled.
5657 VerifyExpectations(!kUpdateDisabled);
5658
5659 cur_test_case_ = std::make_pair(
5660 &ComponentUpdaterPolicyTest::EnabledPolicy_GroupPolicySupported,
5661 &ComponentUpdaterPolicyTest::FinishEnabledPolicy_GroupPolicySupported);
5662 CallAsync(cur_test_case_.first);
5663}
5664
5665void ComponentUpdaterPolicyTest::EnabledPolicy_GroupPolicySupported() {
5666 SetEnableComponentUpdates(true);
5667 UpdateComponent(MakeCrxComponent(true));
5668}
5669
5670void ComponentUpdaterPolicyTest::FinishEnabledPolicy_GroupPolicySupported() {
5671 // Updates enabled policy && policy support -> updates are enabled.
5672 VerifyExpectations(!kUpdateDisabled);
5673
5674 cur_test_case_ = std::make_pair(
5675 &ComponentUpdaterPolicyTest::EnabledPolicy_GroupPolicyNotSupported,
5676 &ComponentUpdaterPolicyTest::FinishEnabledPolicy_GroupPolicyNotSupported);
5677 CallAsync(cur_test_case_.first);
5678}
5679
5680void ComponentUpdaterPolicyTest::EnabledPolicy_GroupPolicyNotSupported() {
5681 SetEnableComponentUpdates(true);
5682 UpdateComponent(MakeCrxComponent(false));
5683}
5684
5685void ComponentUpdaterPolicyTest::FinishEnabledPolicy_GroupPolicyNotSupported() {
5686 // Updates enabled policy && no policy support -> updates are enabled.
5687 VerifyExpectations(!kUpdateDisabled);
5688
5689 cur_test_case_ = std::make_pair(
5690 &ComponentUpdaterPolicyTest::DisabledPolicy_GroupPolicySupported,
5691 &ComponentUpdaterPolicyTest::FinishDisabled_PolicyGroupPolicySupported);
5692 CallAsync(cur_test_case_.first);
5693}
5694
5695void ComponentUpdaterPolicyTest::DisabledPolicy_GroupPolicySupported() {
5696 SetEnableComponentUpdates(false);
5697 UpdateComponent(MakeCrxComponent(true));
5698}
5699
5700void ComponentUpdaterPolicyTest::FinishDisabled_PolicyGroupPolicySupported() {
5701 // Updates enabled policy && policy support -> updates are disabled.
5702 VerifyExpectations(kUpdateDisabled);
5703
5704 cur_test_case_ = std::make_pair(
5705 &ComponentUpdaterPolicyTest::DisabledPolicy_GroupPolicyNotSupported,
5706 &ComponentUpdaterPolicyTest::
5707 FinishDisabledPolicy_GroupPolicyNotSupported);
5708 CallAsync(cur_test_case_.first);
5709}
5710
5711void ComponentUpdaterPolicyTest::DisabledPolicy_GroupPolicyNotSupported() {
5712 SetEnableComponentUpdates(false);
5713 UpdateComponent(MakeCrxComponent(false));
5714}
5715
5716void ComponentUpdaterPolicyTest::
5717 FinishDisabledPolicy_GroupPolicyNotSupported() {
5718 // Updates enabled policy && no policy support -> updates are enabled.
5719 VerifyExpectations(!kUpdateDisabled);
5720
5721 cur_test_case_ = TestCase();
5722 CallAsync(&ComponentUpdaterPolicyTest::EndTest);
5723}
5724
5725IN_PROC_BROWSER_TEST_F(ComponentUpdaterPolicyTest, EnabledComponentUpdates) {
5726 BeginTest();
5727 base::RunLoop().Run();
5728}
5729
[email protected]fb490602013-04-18 17:23:075730#if !defined(OS_CHROMEOS)
5731// Similar to PolicyTest but sets the proper policy before the browser is
5732// started.
5733class PolicyVariationsServiceTest : public PolicyTest {
5734 public:
dcheng32ae6bbb2014-10-22 08:47:295735 void SetUpInProcessBrowserTestFixture() override {
[email protected]fb490602013-04-18 17:23:075736 PolicyTest::SetUpInProcessBrowserTestFixture();
5737 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:095738 policies.Set(key::kVariationsRestrictParameter, POLICY_LEVEL_MANDATORY,
5739 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:305740 std::make_unique<base::Value>("restricted"), nullptr);
[email protected]fb490602013-04-18 17:23:075741 provider_.UpdateChromePolicy(policies);
5742 }
5743};
5744
5745IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
5746 const std::string default_variations_url =
blundell57bcfed2015-09-04 08:44:455747 variations::VariationsService::GetDefaultVariationsServerURLForTesting();
[email protected]fb490602013-04-18 17:23:075748
Ilya Shermanf65350f12017-07-12 19:25:325749 const GURL url =
5750 g_browser_process->variations_service()->GetVariationsServerURL(
Carlos ILa03ca60d2017-12-11 21:43:275751 variations::VariationsService::HttpOptions::USE_HTTPS);
brettw66d1b81b2015-07-06 19:29:405752 EXPECT_TRUE(base::StartsWith(url.spec(), default_variations_url,
5753 base::CompareCase::SENSITIVE));
[email protected]a29ad212013-05-02 20:18:545754 std::string value;
5755 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
5756 EXPECT_EQ("restricted", value);
[email protected]fb490602013-04-18 17:23:075757}
[email protected]4c7d2ca2014-01-09 04:48:295758
5759IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
5760 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:185761 blacklist.AppendString("host.name");
[email protected]4c7d2ca2014-01-09 04:48:295762 PolicyMap policies;
5763 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:095764 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5765 blacklist.CreateDeepCopy(), nullptr);
[email protected]4c7d2ca2014-01-09 04:48:295766 UpdateProviderPolicy(policies);
5767
Michael Giuffridab3783992017-07-22 05:01:035768 EXPECT_EQ(extensions::MessagingDelegate::PolicyPermission::DISALLOW,
Michael Giuffrida9e1a9f82017-08-08 14:23:295769 IsNativeMessagingHostAllowed(browser()->profile(), "host.name"));
5770 EXPECT_EQ(
5771 extensions::MessagingDelegate::PolicyPermission::ALLOW_ALL,
5772 IsNativeMessagingHostAllowed(browser()->profile(), "other.host.name"));
[email protected]4c7d2ca2014-01-09 04:48:295773}
5774
5775IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
5776 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:185777 blacklist.AppendString("*");
[email protected]4c7d2ca2014-01-09 04:48:295778 PolicyMap policies;
5779 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:095780 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5781 blacklist.CreateDeepCopy(), nullptr);
[email protected]4c7d2ca2014-01-09 04:48:295782 UpdateProviderPolicy(policies);
5783
Michael Giuffridab3783992017-07-22 05:01:035784 EXPECT_EQ(extensions::MessagingDelegate::PolicyPermission::DISALLOW,
Michael Giuffrida9e1a9f82017-08-08 14:23:295785 IsNativeMessagingHostAllowed(browser()->profile(), "host.name"));
5786 EXPECT_EQ(
5787 extensions::MessagingDelegate::PolicyPermission::DISALLOW,
5788 IsNativeMessagingHostAllowed(browser()->profile(), "other.host.name"));
[email protected]4c7d2ca2014-01-09 04:48:295789}
5790
5791IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
5792 base::ListValue blacklist;
dchengd9ea63862016-06-03 02:27:185793 blacklist.AppendString("*");
[email protected]4c7d2ca2014-01-09 04:48:295794 base::ListValue whitelist;
dchengd9ea63862016-06-03 02:27:185795 whitelist.AppendString("host.name");
[email protected]4c7d2ca2014-01-09 04:48:295796 PolicyMap policies;
5797 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:095798 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5799 blacklist.CreateDeepCopy(), nullptr);
[email protected]4c7d2ca2014-01-09 04:48:295800 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
dcheng3b344bc22016-05-10 02:26:095801 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5802 whitelist.CreateDeepCopy(), nullptr);
[email protected]4c7d2ca2014-01-09 04:48:295803 UpdateProviderPolicy(policies);
5804
Michael Giuffridab3783992017-07-22 05:01:035805 EXPECT_EQ(extensions::MessagingDelegate::PolicyPermission::ALLOW_ALL,
Michael Giuffrida9e1a9f82017-08-08 14:23:295806 IsNativeMessagingHostAllowed(browser()->profile(), "host.name"));
5807 EXPECT_EQ(
5808 extensions::MessagingDelegate::PolicyPermission::DISALLOW,
5809 IsNativeMessagingHostAllowed(browser()->profile(), "other.host.name"));
[email protected]4c7d2ca2014-01-09 04:48:295810}
5811
5812#endif // !defined(CHROME_OS)
[email protected]fb490602013-04-18 17:23:075813
Lei Zhangc5b042c2017-11-11 00:39:235814#if !defined(OS_CHROMEOS)
zmod6486a62015-07-17 02:20:485815// Sets the hardware acceleration mode policy before the browser is started.
5816class HardwareAccelerationModePolicyTest : public PolicyTest {
5817 public:
5818 HardwareAccelerationModePolicyTest() {}
5819
5820 void SetUpInProcessBrowserTestFixture() override {
5821 PolicyTest::SetUpInProcessBrowserTestFixture();
5822 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:095823 policies.Set(key::kHardwareAccelerationModeEnabled, POLICY_LEVEL_MANDATORY,
5824 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:305825 std::make_unique<base::Value>(false), nullptr);
zmod6486a62015-07-17 02:20:485826 provider_.UpdateChromePolicy(policies);
5827 }
5828};
5829
5830IN_PROC_BROWSER_TEST_F(HardwareAccelerationModePolicyTest,
5831 HardwareAccelerationDisabled) {
5832 // Verifies that hardware acceleration can be disabled with policy.
5833 EXPECT_FALSE(
kinuko7e9da252017-03-10 07:18:425834 content::GpuDataManager::GetInstance()->HardwareAccelerationEnabled());
zmod6486a62015-07-17 02:20:485835}
Lei Zhangc5b042c2017-11-11 00:39:235836#endif // !defined(OS_CHROMEOS)
zmod6486a62015-07-17 02:20:485837
phweissa16ceae22015-09-17 09:33:125838#if defined(OS_CHROMEOS)
5839// Policy is only available in ChromeOS
5840IN_PROC_BROWSER_TEST_F(PolicyTest, UnifiedDesktopEnabledByDefault) {
5841 // Verify that Unified Desktop can be enabled by policy
rjkroege72f8154f2016-10-29 00:49:025842 display::DisplayManager* display_manager =
skycb4be5b2017-04-06 17:52:455843 ash::Shell::Get()->display_manager();
phweissa16ceae22015-09-17 09:33:125844
5845 // The policy description promises that Unified Desktop is not available
5846 // unless the policy is set (or a command line or an extension is used). If
5847 // this default behaviour changes, please change the description at
5848 // components/policy/resources/policy_templates.json.
5849 EXPECT_FALSE(display_manager->unified_desktop_enabled());
5850 // Now set the policy and check that unified desktop is turned on.
5851 PolicyMap policies;
dcheng3b344bc22016-05-10 02:26:095852 policies.Set(key::kUnifiedDesktopEnabledByDefault, POLICY_LEVEL_MANDATORY,
5853 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:195854 base::WrapUnique(new base::Value(true)), nullptr);
phweissa16ceae22015-09-17 09:33:125855 UpdateProviderPolicy(policies);
5856 EXPECT_TRUE(display_manager->unified_desktop_enabled());
dcheng3b344bc22016-05-10 02:26:095857 policies.Set(key::kUnifiedDesktopEnabledByDefault, POLICY_LEVEL_MANDATORY,
5858 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:195859 base::WrapUnique(new base::Value(false)), nullptr);
phweissa16ceae22015-09-17 09:33:125860 UpdateProviderPolicy(policies);
5861 EXPECT_FALSE(display_manager->unified_desktop_enabled());
5862}
pbonde40ccc12016-04-04 15:32:385863
5864class ArcPolicyTest : public PolicyTest {
5865 public:
5866 ArcPolicyTest() {}
5867 ~ArcPolicyTest() override {}
5868
5869 protected:
hidehikoaab3dea2017-01-30 14:36:465870 void SetUpOnMainThread() override {
5871 PolicyTest::SetUpOnMainThread();
Evan Stade70719a792018-04-24 00:13:095872 arc::ArcSessionManager::SetUiEnabledForTesting(false);
hidehiko5cc0f2f482016-12-27 07:14:245873 arc::ArcSessionManager::Get()->SetArcSessionRunnerForTesting(
Jinho Bang2a491912018-01-16 07:21:305874 std::make_unique<arc::ArcSessionRunner>(
Yusuke Sato851bbc22019-03-26 17:16:155875 base::BindRepeating(arc::FakeArcSession::Create)));
pbonde40ccc12016-04-04 15:32:385876
Hidehiko Abe33e9adf2017-09-13 06:12:235877 browser()->profile()->GetPrefs()->SetBoolean(arc::prefs::kArcSignedIn,
5878 true);
5879 browser()->profile()->GetPrefs()->SetBoolean(arc::prefs::kArcTermsAccepted,
hidehiko3b196d32016-12-02 11:05:215880 true);
pbonde40ccc12016-04-04 15:32:385881 }
5882
hidehikoaab3dea2017-01-30 14:36:465883 void TearDownOnMainThread() override {
5884 arc::ArcSessionManager::Get()->Shutdown();
5885 PolicyTest::TearDownOnMainThread();
pbonde40ccc12016-04-04 15:32:385886 }
5887
xdai20e579f2016-06-02 06:58:015888 void SetUpCommandLine(base::CommandLine* command_line) override {
hidehikoaab3dea2017-01-30 14:36:465889 PolicyTest::SetUpCommandLine(command_line);
5890 arc::SetArcAvailableCommandLineForTesting(command_line);
xdai20e579f2016-06-02 06:58:015891 }
5892
khmelaa5c93592016-10-05 16:20:015893 void SetArcEnabledByPolicy(bool enabled) {
5894 PolicyMap policies;
5895 policies.Set(key::kArcEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
5896 POLICY_SOURCE_CLOUD,
jdoerrie239723572017-03-02 12:09:195897 base::WrapUnique(new base::Value(enabled)), nullptr);
khmelaa5c93592016-10-05 16:20:015898 UpdateProviderPolicy(policies);
5899 if (browser()) {
5900 const PrefService* const prefs = browser()->profile()->GetPrefs();
Hidehiko Abe33e9adf2017-09-13 06:12:235901 EXPECT_EQ(prefs->GetBoolean(arc::prefs::kArcEnabled), enabled);
khmelaa5c93592016-10-05 16:20:015902 }
5903 }
5904
pbonde40ccc12016-04-04 15:32:385905 private:
pbonde40ccc12016-04-04 15:32:385906 DISALLOW_COPY_AND_ASSIGN(ArcPolicyTest);
5907};
5908
5909// Test ArcEnabled policy.
5910IN_PROC_BROWSER_TEST_F(ArcPolicyTest, ArcEnabled) {
pbonde40ccc12016-04-04 15:32:385911 const PrefService* const pref = browser()->profile()->GetPrefs();
hidehiko5cc0f2f482016-12-27 07:14:245912 const auto* const arc_session_manager = arc::ArcSessionManager::Get();
pbonde40ccc12016-04-04 15:32:385913
5914 // ARC is switched off by default.
Hidehiko Abe33e9adf2017-09-13 06:12:235915 EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcEnabled));
Hidehiko Abead836ec2017-10-02 13:26:325916 EXPECT_FALSE(arc_session_manager->enable_requested());
pbonde40ccc12016-04-04 15:32:385917
5918 // Enable ARC.
khmelaa5c93592016-10-05 16:20:015919 SetArcEnabledByPolicy(true);
Hidehiko Abead836ec2017-10-02 13:26:325920 EXPECT_TRUE(arc_session_manager->enable_requested());
pbonde40ccc12016-04-04 15:32:385921
5922 // Disable ARC.
khmelaa5c93592016-10-05 16:20:015923 SetArcEnabledByPolicy(false);
Hidehiko Abead836ec2017-10-02 13:26:325924 EXPECT_FALSE(arc_session_manager->enable_requested());
pbonde40ccc12016-04-04 15:32:385925}
alemated70e82f2016-04-05 12:21:335926
Bartosz Fabianowski6979a6d2018-05-24 13:29:205927// Test ArcBackupRestoreServiceEnabled policy.
5928IN_PROC_BROWSER_TEST_F(ArcPolicyTest, ArcBackupRestoreServiceEnabled) {
emaxxf392d832017-02-18 07:01:275929 PrefService* const pref = browser()->profile()->GetPrefs();
poromov1df20032016-07-25 13:02:305930
Bartosz Fabianowski6979a6d2018-05-24 13:29:205931 // Enable ARC backup and restore in user prefs.
5932 pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, true);
poromov1df20032016-07-25 13:02:305933
Bartosz Fabianowski6979a6d2018-05-24 13:29:205934 // ARC backup and restore is disabled by policy by default.
Bartosz Fabianowski0248c492018-07-02 13:44:325935 UpdateProviderPolicy(PolicyMap());
Bartosz Fabianowski6979a6d2018-05-24 13:29:205936 EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
5937 EXPECT_TRUE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
5938
5939 // Set ARC backup and restore to user control via policy.
5940 PolicyMap policies;
5941 policies.Set(key::kArcBackupRestoreServiceEnabled, POLICY_LEVEL_MANDATORY,
5942 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5943 std::make_unique<base::Value>(
5944 static_cast<int>(ArcServicePolicyValue::kUnderUserControl)),
5945 nullptr);
5946 UpdateProviderPolicy(policies);
5947
5948 // User choice should be honored now.
5949 EXPECT_TRUE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
5950 EXPECT_FALSE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
5951 pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, false);
5952 EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
Hidehiko Abe33e9adf2017-09-13 06:12:235953 pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, true);
5954 EXPECT_TRUE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
emaxxf392d832017-02-18 07:01:275955
Bartosz Fabianowski6979a6d2018-05-24 13:29:205956 // Set ARC backup and restore to disabled via policy.
5957 policies.Set(key::kArcBackupRestoreServiceEnabled, POLICY_LEVEL_MANDATORY,
poromov1df20032016-07-25 13:02:305958 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Bartosz Fabianowski6979a6d2018-05-24 13:29:205959 std::make_unique<base::Value>(
5960 static_cast<int>(ArcServicePolicyValue::kDisabled)),
5961 nullptr);
poromov1df20032016-07-25 13:02:305962 UpdateProviderPolicy(policies);
Hidehiko Abe33e9adf2017-09-13 06:12:235963 EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
5964 EXPECT_TRUE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
Bartosz Fabianowskicd76af12019-04-12 07:53:055965
5966 // Disable ARC backup and restore in user prefs.
5967 pref->SetBoolean(arc::prefs::kArcBackupRestoreEnabled, true);
5968
5969 // Set ARC backup and restore to enabled via policy.
5970 policies.Set(key::kArcBackupRestoreServiceEnabled, POLICY_LEVEL_MANDATORY,
5971 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
5972 std::make_unique<base::Value>(
5973 static_cast<int>(ArcServicePolicyValue::kEnabled)),
5974 nullptr);
5975 UpdateProviderPolicy(policies);
5976 EXPECT_TRUE(pref->GetBoolean(arc::prefs::kArcBackupRestoreEnabled));
5977 EXPECT_TRUE(pref->IsManagedPreference(arc::prefs::kArcBackupRestoreEnabled));
poromov1df20032016-07-25 13:02:305978}
5979
Bartosz Fabianowski6979a6d2018-05-24 13:29:205980// Test ArcGoogleLocationServicesEnabled policy and its interplay with the
emaxxd996b35e2017-02-06 17:03:475981// DefaultGeolocationSetting policy.
Bartosz Fabianowski6979a6d2018-05-24 13:29:205982IN_PROC_BROWSER_TEST_F(ArcPolicyTest, ArcGoogleLocationServicesEnabled) {
emaxxf392d832017-02-18 07:01:275983 PrefService* const pref = browser()->profile()->GetPrefs();
khmel75cf0e72016-08-17 16:45:175984
Bartosz Fabianowski6979a6d2018-05-24 13:29:205985 // Values of the ArcGoogleLocationServicesEnabled policy to be tested.
jdoerriecc9f5732017-08-23 14:12:305986 std::vector<base::Value> test_policy_values;
Bartosz Fabianowski6979a6d2018-05-24 13:29:205987 test_policy_values.emplace_back(); // unset
5988 test_policy_values.emplace_back(
5989 static_cast<int>(ArcServicePolicyValue::kDisabled));
5990 test_policy_values.emplace_back(
5991 static_cast<int>(ArcServicePolicyValue::kUnderUserControl));
Bartosz Fabianowskicd76af12019-04-12 07:53:055992 test_policy_values.emplace_back(
5993 static_cast<int>(ArcServicePolicyValue::kEnabled));
jdoerriecc9f5732017-08-23 14:12:305994
emaxxd996b35e2017-02-06 17:03:475995 // Values of the DefaultGeolocationSetting policy to be tested.
jdoerriecc9f5732017-08-23 14:12:305996 std::vector<base::Value> test_default_geo_policy_values;
5997 test_default_geo_policy_values.emplace_back(); // unset
5998 test_default_geo_policy_values.emplace_back(1); // 'AllowGeolocation'
5999 test_default_geo_policy_values.emplace_back(2); // 'BlockGeolocation'
6000 test_default_geo_policy_values.emplace_back(3); // 'AskGeolocation'
khmel75cf0e72016-08-17 16:45:176001
Bartosz Fabianowski6979a6d2018-05-24 13:29:206002 // Switch on the pref in user prefs.
Hidehiko Abe33e9adf2017-09-13 06:12:236003 pref->SetBoolean(arc::prefs::kArcLocationServiceEnabled, true);
Bartosz Fabianowski6979a6d2018-05-24 13:29:206004
6005 // The pref is overridden to disabled by policy by default.
Bartosz Fabianowski0248c492018-07-02 13:44:326006 UpdateProviderPolicy(PolicyMap());
Bartosz Fabianowskicd76af12019-04-12 07:53:056007 EXPECT_FALSE(pref->GetBoolean(arc::prefs::kArcLocationServiceEnabled));
6008 EXPECT_TRUE(
6009 pref->IsManagedPreference(arc::prefs::kArcLocationServiceEnabled));
emaxxf392d832017-02-18 07:01:276010
emaxxd996b35e2017-02-06 17:03:476011 for (const auto& test_policy_value : test_policy_values) {
6012 for (const auto& test_default_geo_policy_value :
6013 test_default_geo_policy_values) {
6014 PolicyMap policies;
Bartosz Fabianowski6979a6d2018-05-24 13:29:206015 if (test_policy_value.is_int()) {
6016 policies.Set(key::kArcGoogleLocationServicesEnabled,
6017 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
6018 POLICY_SOURCE_CLOUD, test_policy_value.CreateDeepCopy(),
6019 nullptr);
emaxxd996b35e2017-02-06 17:03:476020 }
6021 if (test_default_geo_policy_value.is_int()) {
6022 policies.Set(key::kDefaultGeolocationSetting, POLICY_LEVEL_MANDATORY,
6023 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
6024 test_default_geo_policy_value.CreateDeepCopy(), nullptr);
6025 }
6026 UpdateProviderPolicy(policies);
khmel75cf0e72016-08-17 16:45:176027
emaxxd996b35e2017-02-06 17:03:476028 const bool should_be_disabled_by_policy =
Bartosz Fabianowski6979a6d2018-05-24 13:29:206029 test_policy_value.is_none() ||
6030 (test_policy_value.GetInt() ==
6031 static_cast<int>(ArcServicePolicyValue::kDisabled));
Bartosz Fabianowskicd76af12019-04-12 07:53:056032 const bool should_be_enabled_by_policy =
6033 test_policy_value.is_int() &&
6034 test_policy_value.GetInt() ==
6035 static_cast<int>(ArcServicePolicyValue::kEnabled);
emaxxd996b35e2017-02-06 17:03:476036 const bool should_be_disabled_by_default_geo_policy =
6037 test_default_geo_policy_value.is_int() &&
6038 test_default_geo_policy_value.GetInt() == 2;
6039 const bool expected_pref_value =
6040 !(should_be_disabled_by_policy ||
6041 should_be_disabled_by_default_geo_policy);
6042 EXPECT_EQ(expected_pref_value,
Hidehiko Abe33e9adf2017-09-13 06:12:236043 pref->GetBoolean(arc::prefs::kArcLocationServiceEnabled))
Bartosz Fabianowskicd76af12019-04-12 07:53:056044 << "ArcGoogleLocationServicesEnabled policy is set to "
6045 << test_policy_value << "DefaultGeolocationSetting policy is set to "
emaxxd996b35e2017-02-06 17:03:476046 << test_default_geo_policy_value;
khmel75cf0e72016-08-17 16:45:176047
emaxxd996b35e2017-02-06 17:03:476048 const bool expected_pref_managed =
Bartosz Fabianowskicd76af12019-04-12 07:53:056049 should_be_disabled_by_policy || should_be_enabled_by_policy ||
Bartosz Fabianowski6979a6d2018-05-24 13:29:206050 should_be_disabled_by_default_geo_policy;
Hidehiko Abe33e9adf2017-09-13 06:12:236051 EXPECT_EQ(
6052 expected_pref_managed,
6053 pref->IsManagedPreference(arc::prefs::kArcLocationServiceEnabled))
Bartosz Fabianowskicd76af12019-04-12 07:53:056054 << "ArcGoogleLocationServicesEnabled policy is set to "
6055 << test_policy_value << "DefaultGeolocationSetting policy is set to "
emaxxd996b35e2017-02-06 17:03:476056 << test_default_geo_policy_value;
6057 }
6058 }
khmel75cf0e72016-08-17 16:45:176059}
6060
thestigf80564462015-09-29 23:12:086061#endif // defined(OS_CHROMEOS)
phweissa16ceae22015-09-17 09:33:126062
Carlos IL5a9e7512019-06-13 22:35:286063class NetworkTimePolicyTest : public PolicyTest {
estark80618c32017-05-24 02:48:316064 public:
Carlos IL0ea4e592018-05-11 01:51:576065 NetworkTimePolicyTest() {}
chaopeng01e3b252017-10-18 22:33:376066 ~NetworkTimePolicyTest() override {}
6067
6068 void SetUpOnMainThread() override {
6069 std::map<std::string, std::string> parameters;
6070 parameters["FetchBehavior"] = "on-demand-only";
6071 scoped_feature_list_.InitAndEnableFeatureWithParameters(
6072 network_time::kNetworkTimeServiceQuerying, parameters);
6073 PolicyTest::SetUpOnMainThread();
isherman9fb15b82017-06-10 01:30:346074 }
6075
estark80618c32017-05-24 02:48:316076 // A request handler that returns a dummy response and counts the number of
6077 // times it is called.
6078 std::unique_ptr<net::test_server::HttpResponse> CountingRequestHandler(
6079 const net::test_server::HttpRequest& request) {
6080 net::test_server::BasicHttpResponse* response =
6081 new net::test_server::BasicHttpResponse();
6082 num_requests_++;
6083 response->set_code(net::HTTP_OK);
6084 response->set_content(
6085 ")]}'\n"
6086 "{\"current_time_millis\":1461621971825,\"server_nonce\":-6."
6087 "006853099049523E85}");
6088 response->AddCustomHeader("x-cup-server-proof", "dead:beef");
6089 return std::unique_ptr<net::test_server::HttpResponse>(response);
6090 }
6091
6092 uint32_t num_requests() { return num_requests_; }
6093
6094 private:
chaopeng01e3b252017-10-18 22:33:376095 base::test::ScopedFeatureList scoped_feature_list_;
estark80618c32017-05-24 02:48:316096 uint32_t num_requests_ = 0;
chaopeng01e3b252017-10-18 22:33:376097
6098 DISALLOW_COPY_AND_ASSIGN(NetworkTimePolicyTest);
estark80618c32017-05-24 02:48:316099};
6100
Carlos IL5a9e7512019-06-13 22:35:286101IN_PROC_BROWSER_TEST_F(NetworkTimePolicyTest, NetworkTimeQueriesDisabled) {
estark80618c32017-05-24 02:48:316102 // Set a policy to disable network time queries.
6103 PolicyMap policies;
estark9a1fe802017-06-01 15:50:176104 policies.Set(key::kBrowserNetworkTimeQueriesEnabled, POLICY_LEVEL_MANDATORY,
estark80618c32017-05-24 02:48:316105 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:306106 std::make_unique<base::Value>(false), nullptr);
estark80618c32017-05-24 02:48:316107 UpdateProviderPolicy(policies);
6108
6109 embedded_test_server()->RegisterRequestHandler(base::Bind(
6110 &NetworkTimePolicyTest::CountingRequestHandler, base::Unretained(this)));
6111 ASSERT_TRUE(embedded_test_server()->Start());
6112 g_browser_process->network_time_tracker()->SetTimeServerURLForTesting(
6113 embedded_test_server()->GetURL("/"));
6114
6115 net::EmbeddedTestServer https_server_expired_(
6116 net::EmbeddedTestServer::TYPE_HTTPS);
6117 https_server_expired_.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
6118 ASSERT_TRUE(https_server_expired_.Start());
6119
6120 // Navigate to a page with a certificate date error and then check that a
6121 // network time query was not sent.
6122 ui_test_utils::NavigateToURL(browser(), https_server_expired_.GetURL("/"));
6123 content::WebContents* tab =
6124 browser()->tab_strip_model()->GetActiveWebContents();
Carlos IL0ea4e592018-05-11 01:51:576125 WaitForInterstitial(tab);
estark80618c32017-05-24 02:48:316126 EXPECT_EQ(0u, num_requests());
6127
6128 // Now enable the policy and check that a network time query is sent.
estark9a1fe802017-06-01 15:50:176129 policies.Set(key::kBrowserNetworkTimeQueriesEnabled, POLICY_LEVEL_MANDATORY,
estark80618c32017-05-24 02:48:316130 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
Jinho Bang2a491912018-01-16 07:21:306131 std::make_unique<base::Value>(true), nullptr);
estark80618c32017-05-24 02:48:316132 UpdateProviderPolicy(policies);
6133 ui_test_utils::NavigateToURL(browser(), https_server_expired_.GetURL("/"));
Carlos IL0ea4e592018-05-11 01:51:576134 EXPECT_TRUE(IsShowingInterstitial(tab));
estark80618c32017-05-24 02:48:316135 EXPECT_EQ(1u, num_requests());
6136}
6137
Toni Barzicc45d9b12017-07-25 02:53:366138#if defined(OS_CHROMEOS)
6139
6140class NoteTakingOnLockScreenPolicyTest : public PolicyTest {
6141 public:
6142 NoteTakingOnLockScreenPolicyTest() = default;
6143 ~NoteTakingOnLockScreenPolicyTest() override = default;
6144
6145 void SetUpCommandLine(base::CommandLine* command_line) override {
Toni Barzicc45d9b12017-07-25 02:53:366146 // An app requires lockScreen permission to be enabled as a lock screen app.
6147 // This permission is protected by a whitelist, so the test app has to be
6148 // whitelisted as well.
6149 command_line->AppendSwitchASCII(
6150 extensions::switches::kWhitelistedExtensionID, kTestAppId);
Toni Barzic579f2d02017-09-22 23:57:236151 command_line->AppendSwitch(ash::switches::kAshForceEnableStylusTools);
Toni Barzicc45d9b12017-07-25 02:53:366152 PolicyTest::SetUpCommandLine(command_line);
6153 }
6154
6155 void SetUserLevelPrefValue(const std::string& app_id,
6156 bool enabled_on_lock_screen) {
6157 chromeos::NoteTakingHelper* helper = chromeos::NoteTakingHelper::Get();
6158 ASSERT_TRUE(helper);
6159
6160 helper->SetPreferredApp(browser()->profile(), app_id);
6161 helper->SetPreferredAppEnabledOnLockScreen(browser()->profile(),
6162 enabled_on_lock_screen);
6163 }
6164
6165 void SetPolicyValue(std::unique_ptr<base::Value> value) {
6166 PolicyMap policies;
6167 if (value) {
6168 policies.Set(key::kNoteTakingAppsLockScreenWhitelist,
6169 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
6170 POLICY_SOURCE_CLOUD, std::move(value), nullptr);
6171 }
6172 UpdateProviderPolicy(policies);
6173 }
6174
6175 chromeos::NoteTakingLockScreenSupport GetAppLockScreenStatus(
6176 const std::string& app_id) {
6177 std::unique_ptr<chromeos::NoteTakingAppInfo> info =
6178 chromeos::NoteTakingHelper::Get()->GetPreferredChromeAppInfo(
6179 browser()->profile());
6180 if (!info || info->app_id != app_id)
6181 return chromeos::NoteTakingLockScreenSupport::kNotSupported;
6182 return info->lock_screen_support;
6183 }
6184
6185 // The test app ID.
6186 static const char kTestAppId[];
6187
6188 private:
6189 DISALLOW_COPY_AND_ASSIGN(NoteTakingOnLockScreenPolicyTest);
6190};
6191
6192const char NoteTakingOnLockScreenPolicyTest::kTestAppId[] =
6193 "cadfeochfldmbdgoccgbeianhamecbae";
6194
6195IN_PROC_BROWSER_TEST_F(NoteTakingOnLockScreenPolicyTest,
6196 DisableLockScreenNoteTakingByPolicy) {
6197 scoped_refptr<const extensions::Extension> app =
6198 LoadUnpackedExtension("lock_screen_apps/app_launch");
6199 ASSERT_TRUE(app);
6200 ASSERT_EQ(kTestAppId, app->id());
6201
6202 SetUserLevelPrefValue(app->id(), true);
6203 EXPECT_EQ(chromeos::NoteTakingLockScreenSupport::kEnabled,
6204 GetAppLockScreenStatus(app->id()));
6205
Jinho Bang2a491912018-01-16 07:21:306206 SetPolicyValue(std::make_unique<base::ListValue>());
Toni Barzicc45d9b12017-07-25 02:53:366207 EXPECT_EQ(chromeos::NoteTakingLockScreenSupport::kNotAllowedByPolicy,
6208 GetAppLockScreenStatus(app->id()));
6209
6210 SetPolicyValue(nullptr);
6211 EXPECT_EQ(chromeos::NoteTakingLockScreenSupport::kEnabled,
6212 GetAppLockScreenStatus(app->id()));
6213}
6214
6215IN_PROC_BROWSER_TEST_F(NoteTakingOnLockScreenPolicyTest,
6216 WhitelistLockScreenNoteTakingAppByPolicy) {
6217 scoped_refptr<const extensions::Extension> app =
6218 LoadUnpackedExtension("lock_screen_apps/app_launch");
6219 ASSERT_TRUE(app);
6220 ASSERT_EQ(kTestAppId, app->id());
6221
6222 SetUserLevelPrefValue(app->id(), false);
6223 EXPECT_EQ(chromeos::NoteTakingLockScreenSupport::kSupported,
6224 GetAppLockScreenStatus(app->id()));
6225
Jinho Bang2a491912018-01-16 07:21:306226 auto policy = std::make_unique<base::ListValue>();
Toni Barzicc45d9b12017-07-25 02:53:366227 policy->GetList().emplace_back(base::Value(kTestAppId));
6228 SetPolicyValue(std::move(policy));
6229
6230 EXPECT_EQ(chromeos::NoteTakingLockScreenSupport::kSupported,
6231 GetAppLockScreenStatus(app->id()));
6232
6233 SetUserLevelPrefValue(app->id(), true);
6234 EXPECT_EQ(chromeos::NoteTakingLockScreenSupport::kEnabled,
6235 GetAppLockScreenStatus(app->id()));
6236}
6237
6238#endif // defined(OS_CHROMEOS)
6239
François Beaufort4f8107d2018-03-05 12:12:106240#if !defined(OS_ANDROID)
6241
Becca Hughesfe8c32c2018-03-21 13:36:566242class AutoplayPolicyTest : public PolicyTest {
6243 public:
6244 AutoplayPolicyTest() {
6245 // Start two embedded test servers on different ports. This will ensure
6246 // the test works correctly with cross origin iframes and site-per-process.
Alan Cuttera9a96c52019-03-28 07:15:396247 embedded_test_server2()->AddDefaultHandlers(GetChromeTestDataDir());
Becca Hughesfe8c32c2018-03-21 13:36:566248 EXPECT_TRUE(embedded_test_server()->Start());
6249 EXPECT_TRUE(embedded_test_server2()->Start());
6250 }
6251
6252 void NavigateToTestPage() {
6253 GURL origin = embedded_test_server()->GetURL(kAutoplayTestPageURL);
6254 ui_test_utils::NavigateToURL(browser(), origin);
6255
6256 // Navigate the subframe to the test page but on the second origin.
6257 GURL origin2 = embedded_test_server2()->GetURL(kAutoplayTestPageURL);
6258 std::string script = base::StringPrintf(
6259 "setTimeout(\""
6260 "document.getElementById('subframe').src='%s';"
6261 "\",0)",
6262 origin2.spec().c_str());
6263 content::TestNavigationObserver load_observer(GetWebContents());
6264 EXPECT_TRUE(ExecuteScriptWithoutUserGesture(GetWebContents(), script));
6265 load_observer.Wait();
6266 }
6267
6268 net::EmbeddedTestServer* embedded_test_server2() {
6269 return &embedded_test_server2_;
6270 }
6271
6272 bool TryAutoplay(content::RenderFrameHost* rfh) {
6273 bool result = false;
6274
6275 EXPECT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractBool(
6276 rfh, "tryPlayback();", &result));
6277
6278 return result;
6279 }
6280
6281 content::WebContents* GetWebContents() {
6282 return browser()->tab_strip_model()->GetActiveWebContents();
6283 }
6284
6285 content::RenderFrameHost* GetMainFrame() {
6286 return GetWebContents()->GetMainFrame();
6287 }
6288
6289 content::RenderFrameHost* GetChildFrame() {
6290 return GetWebContents()->GetAllFrames()[1];
6291 }
6292
6293 private:
6294 // Second instance of embedded test server to provide a second test origin.
6295 net::EmbeddedTestServer embedded_test_server2_;
6296};
6297
6298IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayAllowedByPolicy) {
6299 NavigateToTestPage();
François Beaufort4f8107d2018-03-05 12:12:106300
6301 // Check that autoplay was not allowed.
Becca Hughesfe8c32c2018-03-21 13:36:566302 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6303 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
François Beaufort4f8107d2018-03-05 12:12:106304
6305 // Update policy to allow autoplay.
6306 PolicyMap policies;
6307 SetPolicy(&policies, key::kAutoplayAllowed,
6308 std::make_unique<base::Value>(true));
6309 UpdateProviderPolicy(policies);
6310
6311 // Check that autoplay was allowed by policy.
Becca Hughesfe8c32c2018-03-21 13:36:566312 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6313 EXPECT_TRUE(TryAutoplay(GetMainFrame()));
6314 EXPECT_TRUE(TryAutoplay(GetChildFrame()));
6315}
6316
6317IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayWhitelist_Allowed) {
6318 NavigateToTestPage();
6319
6320 // Check that autoplay was not allowed.
6321 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6322 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6323
6324 // Create a test whitelist with our origin.
6325 std::vector<base::Value> whitelist;
6326 whitelist.push_back(base::Value(embedded_test_server()->GetURL("/").spec()));
6327
6328 // Update policy to allow autoplay for our test origin.
6329 PolicyMap policies;
6330 SetPolicy(&policies, key::kAutoplayWhitelist,
6331 std::make_unique<base::ListValue>(whitelist));
6332 UpdateProviderPolicy(policies);
6333
6334 // Check that autoplay was allowed by policy.
6335 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6336 EXPECT_TRUE(TryAutoplay(GetMainFrame()));
6337 EXPECT_TRUE(TryAutoplay(GetChildFrame()));
6338}
6339
6340IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayWhitelist_PatternAllowed) {
6341 NavigateToTestPage();
6342
6343 // Check that autoplay was not allowed.
6344 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6345 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6346
6347 // Create a test whitelist with our origin.
6348 std::vector<base::Value> whitelist;
6349 whitelist.push_back(base::Value("127.0.0.1:*"));
6350
6351 // Update policy to allow autoplay for our test origin.
6352 PolicyMap policies;
6353 SetPolicy(&policies, key::kAutoplayWhitelist,
6354 std::make_unique<base::ListValue>(whitelist));
6355 UpdateProviderPolicy(policies);
6356
6357 // Check that autoplay was allowed by policy.
6358 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6359 EXPECT_TRUE(TryAutoplay(GetMainFrame()));
6360 EXPECT_TRUE(TryAutoplay(GetChildFrame()));
6361}
6362
6363IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayWhitelist_Missing) {
6364 NavigateToTestPage();
6365
6366 // Check that autoplay was not allowed.
6367 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6368 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6369
6370 // Create a test whitelist with a random origin.
6371 std::vector<base::Value> whitelist;
6372 whitelist.push_back(base::Value("https://www.example.com"));
6373
6374 // Update policy to allow autoplay for a random origin.
6375 PolicyMap policies;
6376 SetPolicy(&policies, key::kAutoplayWhitelist,
6377 std::make_unique<base::ListValue>(whitelist));
6378 UpdateProviderPolicy(policies);
6379
6380 // Check that autoplay was not allowed.
6381 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6382 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6383 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6384}
6385
6386IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayDeniedByPolicy) {
6387 NavigateToTestPage();
6388
6389 // Check that autoplay was not allowed.
6390 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6391 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6392
6393 // Update policy to forbid autoplay.
6394 PolicyMap policies;
6395 SetPolicy(&policies, key::kAutoplayAllowed,
6396 std::make_unique<base::Value>(false));
6397 UpdateProviderPolicy(policies);
6398
6399 // Check that autoplay was not allowed by policy.
6400 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6401 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6402 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6403
6404 // Create a test whitelist with a random origin.
6405 std::vector<base::Value> whitelist;
6406 whitelist.push_back(base::Value("https://www.example.com"));
6407
6408 // Update policy to allow autoplay for a random origin.
6409 SetPolicy(&policies, key::kAutoplayWhitelist,
6410 std::make_unique<base::ListValue>(whitelist));
6411 UpdateProviderPolicy(policies);
6412
6413 // Check that autoplay was not allowed.
6414 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6415 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6416 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6417}
6418
6419IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayDeniedAllowedWithURL) {
6420 NavigateToTestPage();
6421
6422 // Check that autoplay was not allowed.
6423 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6424 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6425
6426 // Update policy to forbid autoplay.
6427 PolicyMap policies;
6428 SetPolicy(&policies, key::kAutoplayAllowed,
6429 std::make_unique<base::Value>(false));
6430 UpdateProviderPolicy(policies);
6431
6432 // Check that autoplay was not allowed by policy.
6433 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6434 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6435 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6436
6437 // Create a test whitelist with our test origin.
6438 std::vector<base::Value> whitelist;
6439 whitelist.push_back(base::Value(embedded_test_server()->GetURL("/").spec()));
6440
6441 // Update policy to allow autoplay for our test origin.
6442 SetPolicy(&policies, key::kAutoplayWhitelist,
6443 std::make_unique<base::ListValue>(whitelist));
6444 UpdateProviderPolicy(policies);
6445
6446 // Check that autoplay was allowed by policy.
6447 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6448 EXPECT_TRUE(TryAutoplay(GetMainFrame()));
6449 EXPECT_TRUE(TryAutoplay(GetChildFrame()));
6450}
6451
6452IN_PROC_BROWSER_TEST_F(AutoplayPolicyTest, AutoplayAllowedGlobalAndURL) {
6453 NavigateToTestPage();
6454
6455 // Check that autoplay was not allowed.
6456 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6457 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6458
6459 // Update policy to forbid autoplay.
6460 PolicyMap policies;
6461 SetPolicy(&policies, key::kAutoplayAllowed,
6462 std::make_unique<base::Value>(false));
6463 UpdateProviderPolicy(policies);
6464
6465 // Check that autoplay was not allowed by policy.
6466 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6467 EXPECT_FALSE(TryAutoplay(GetMainFrame()));
6468 EXPECT_FALSE(TryAutoplay(GetChildFrame()));
6469
6470 // Create a test whitelist with our test origin.
6471 std::vector<base::Value> whitelist;
6472 whitelist.push_back(base::Value(embedded_test_server()->GetURL("/").spec()));
6473
6474 // Update policy to allow autoplay for our test origin.
6475 SetPolicy(&policies, key::kAutoplayWhitelist,
6476 std::make_unique<base::ListValue>(whitelist));
6477 UpdateProviderPolicy(policies);
6478
6479 // Check that autoplay was allowed by policy.
6480 GetWebContents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
6481 EXPECT_TRUE(TryAutoplay(GetMainFrame()));
6482 EXPECT_TRUE(TryAutoplay(GetChildFrame()));
François Beaufort4f8107d2018-03-05 12:12:106483}
6484
6485#endif // !defined(OS_ANDROID)
6486
Reilly Grant6f18e1f2018-04-03 02:03:226487IN_PROC_BROWSER_TEST_F(PolicyTest, WebUsbDefault) {
Reilly Grant2e64da32019-04-23 18:06:476488 const auto kTestOrigin = url::Origin::Create(GURL("https://foo.com:443"));
Reilly Grant6f18e1f2018-04-03 02:03:226489
6490 // Expect the default permission value to be 'ask'.
6491 auto* context = UsbChooserContextFactory::GetForProfile(browser()->profile());
Reilly Grant2e64da32019-04-23 18:06:476492 EXPECT_TRUE(context->CanRequestObjectPermission(kTestOrigin, kTestOrigin));
Reilly Grant6f18e1f2018-04-03 02:03:226493
6494 // Update policy to change the default permission value to 'block'.
6495 PolicyMap policies;
6496 SetPolicy(&policies, key::kDefaultWebUsbGuardSetting,
6497 std::make_unique<base::Value>(2));
6498 UpdateProviderPolicy(policies);
Reilly Grant2e64da32019-04-23 18:06:476499 EXPECT_FALSE(context->CanRequestObjectPermission(kTestOrigin, kTestOrigin));
Reilly Grant6f18e1f2018-04-03 02:03:226500
6501 // Update policy to change the default permission value to 'ask'.
6502 SetPolicy(&policies, key::kDefaultWebUsbGuardSetting,
6503 std::make_unique<base::Value>(3));
6504 UpdateProviderPolicy(policies);
Reilly Grant2e64da32019-04-23 18:06:476505 EXPECT_TRUE(context->CanRequestObjectPermission(kTestOrigin, kTestOrigin));
Reilly Grant6f18e1f2018-04-03 02:03:226506}
6507
Ovidio Henriqueze3aa8a562018-10-09 15:49:156508IN_PROC_BROWSER_TEST_F(PolicyTest, WebUsbAllowDevicesForUrls) {
Reilly Grant392c6112019-04-23 19:12:126509 const auto kTestOrigin = url::Origin::Create(GURL("https://foo.com:443"));
Donna Wufd06ab32019-05-07 16:39:326510 scoped_refptr<device::FakeUsbDeviceInfo> device =
6511 base::MakeRefCounted<device::FakeUsbDeviceInfo>(0, 0, "Google", "Gizmo",
6512 "123ABC");
6513 const auto& device_info = device->GetDeviceInfo();
Ovidio Henriqueze3aa8a562018-10-09 15:49:156514
6515 // Expect the default permission value to be empty.
6516 auto* context = UsbChooserContextFactory::GetForProfile(browser()->profile());
Reilly Grant392c6112019-04-23 19:12:126517 EXPECT_FALSE(
Donna Wufd06ab32019-05-07 16:39:326518 context->HasDevicePermission(kTestOrigin, kTestOrigin, device_info));
Ovidio Henriqueze3aa8a562018-10-09 15:49:156519
Reilly Grant392c6112019-04-23 19:12:126520 // Update policy to add an entry to the permission value to allow
6521 // |kTestOrigin| to access the device described by |device_info|.
Ovidio Henriqueze3aa8a562018-10-09 15:49:156522 PolicyMap policies;
6523
6524 base::Value device_value(base::Value::Type::DICTIONARY);
6525 device_value.SetKey("vendor_id", base::Value(0));
6526 device_value.SetKey("product_id", base::Value(0));
6527
6528 base::Value devices_value(base::Value::Type::LIST);
6529 devices_value.GetList().push_back(std::move(device_value));
6530
Ovidio Henriquezc6b23f12018-11-15 21:26:316531 base::Value urls_value(base::Value::Type::LIST);
6532 urls_value.GetList().emplace_back(base::Value("https://foo.com"));
Ovidio Henriqueze3aa8a562018-10-09 15:49:156533
6534 base::Value entry(base::Value::Type::DICTIONARY);
6535 entry.SetKey("devices", std::move(devices_value));
Ovidio Henriquezc6b23f12018-11-15 21:26:316536 entry.SetKey("urls", std::move(urls_value));
Ovidio Henriqueze3aa8a562018-10-09 15:49:156537
6538 auto policy_value = std::make_unique<base::Value>(base::Value::Type::LIST);
6539 policy_value->GetList().push_back(std::move(entry));
6540
6541 SetPolicy(&policies, key::kWebUsbAllowDevicesForUrls,
6542 std::move(policy_value));
6543 UpdateProviderPolicy(policies);
6544
Reilly Grant392c6112019-04-23 19:12:126545 EXPECT_TRUE(
Donna Wufd06ab32019-05-07 16:39:326546 context->HasDevicePermission(kTestOrigin, kTestOrigin, device_info));
Ovidio Henriqueze3aa8a562018-10-09 15:49:156547
6548 // Remove the policy to ensure that it can be dynamically updated.
6549 SetPolicy(&policies, key::kWebUsbAllowDevicesForUrls,
6550 std::make_unique<base::Value>(base::Value::Type::LIST));
6551 UpdateProviderPolicy(policies);
6552
Reilly Grant392c6112019-04-23 19:12:126553 EXPECT_FALSE(
Donna Wufd06ab32019-05-07 16:39:326554 context->HasDevicePermission(kTestOrigin, kTestOrigin, device_info));
Ovidio Henriqueze3aa8a562018-10-09 15:49:156555}
6556
Oleg Davydov2cc0167b2019-02-05 14:32:486557// Handler for embedded http-server, returns a small page with javascript
6558// variable and a link to increment it. It's for JavascriptBlacklistable test.
6559std::unique_ptr<net::test_server::HttpResponse> JSIncrementerPageHandler(
6560 const net::test_server::HttpRequest& request) {
6561 if (request.relative_url != "/test.html") {
6562 return std::unique_ptr<net::test_server::HttpResponse>();
6563 }
6564
6565 std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
6566 new net::test_server::BasicHttpResponse());
6567 http_response->set_code(net::HTTP_OK);
6568 http_response->set_content(
6569 "<head><script type=\"text/javascript\">\n"
6570 "<!--\n"
6571 "var value = 1;"
6572 "var increment = function() {"
6573 " value = value + 1;"
6574 "};\n"
6575 "//-->\n"
6576 "</script></head><body>"
6577 "<a id='link' href=\"javascript:increment();\">click</a>"
6578 "</body>");
6579 http_response->set_content_type("text/html");
6580 return http_response;
6581}
6582
6583// Fetch value from page generated by JSIncrementerPageHandler.
6584int JSIncrementerFetch(content::WebContents* contents) {
6585 int result;
6586 EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
6587 contents, "domAutomationController.send(value);", &result));
6588 return result;
6589}
6590
6591// Tests that javascript-links are handled properly according to blacklist
6592// settings, bug 913334.
6593IN_PROC_BROWSER_TEST_F(PolicyTest, JavascriptBlacklistable) {
6594 embedded_test_server()->RegisterRequestHandler(
6595 base::BindRepeating(&JSIncrementerPageHandler));
6596 ASSERT_TRUE(embedded_test_server()->Start());
6597 content::WebContents* contents =
6598 browser()->tab_strip_model()->GetActiveWebContents();
6599 ui_test_utils::NavigateToURL(browser(),
6600 embedded_test_server()->GetURL("/test.html"));
6601
6602 EXPECT_EQ(JSIncrementerFetch(contents), 1);
6603
6604 // Without blacklist policy value is incremented properly.
6605 ui_test_utils::NavigateToURLWithDisposition(
6606 browser(), GURL("javascript:increment()"),
6607 WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
6608
6609 EXPECT_EQ(JSIncrementerFetch(contents), 2);
6610
6611 // Create and apply a policy.
6612 base::ListValue blacklist;
6613 blacklist.AppendString("javascript://*");
6614 PolicyMap policies;
6615 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
6616 POLICY_SOURCE_CLOUD, blacklist.CreateDeepCopy(), nullptr);
6617 UpdateProviderPolicy(policies);
6618 FlushBlacklistPolicy();
6619
6620 // After applying policy javascript url's don't work any more, value leaves
6621 // unchanged.
6622 ui_test_utils::NavigateToURLWithDisposition(
6623 browser(), GURL("javascript:increment()"),
6624 WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
6625 EXPECT_EQ(JSIncrementerFetch(contents), 2);
6626
6627 // But in-page links still work even if they are javascript-links.
6628 EXPECT_TRUE(content::ExecuteScript(
6629 contents, "document.getElementById('link').click();"));
6630 EXPECT_EQ(JSIncrementerFetch(contents), 3);
6631}
6632
Giovanni Ortuño Urquidi77b5bf72018-08-23 06:43:296633// Similar to PolicyTest but sets the WebAppInstallForceList policy before the
6634// browser is started.
6635class WebAppInstallForceListPolicyTest : public PolicyTest {
6636 public:
6637 WebAppInstallForceListPolicyTest() {}
6638 ~WebAppInstallForceListPolicyTest() override {}
6639
6640 void SetUpInProcessBrowserTestFixture() override {
6641 PolicyTest::SetUpInProcessBrowserTestFixture();
6642 ASSERT_TRUE(embedded_test_server()->Start());
6643
6644 policy_app_url_ =
6645 embedded_test_server()->GetURL("/banners/manifest_test_page.html");
6646 base::Value url(policy_app_url_.spec());
6647 base::Value launch_container("window");
6648
6649 base::Value item(base::Value::Type::DICTIONARY);
6650 item.SetKey("url", std::move(url));
Giovanni Ortuño Urquidi02a578212019-03-28 01:57:406651 item.SetKey("default_launch_container", std::move(launch_container));
Giovanni Ortuño Urquidi77b5bf72018-08-23 06:43:296652
6653 base::Value list(base::Value::Type::LIST);
6654 list.GetList().push_back(std::move(item));
6655
6656 PolicyMap policies;
6657 SetPolicy(&policies, key::kWebAppInstallForceList,
6658 base::Value::ToUniquePtrValue(std::move(list)));
6659 provider_.UpdateChromePolicy(policies);
6660 }
6661
6662 protected:
6663 GURL policy_app_url_;
6664
6665 private:
6666 DISALLOW_COPY_AND_ASSIGN(WebAppInstallForceListPolicyTest);
6667};
6668
Giovanni Ortuño Urquidi273c6072019-06-13 07:15:366669IN_PROC_BROWSER_TEST_F(WebAppInstallForceListPolicyTest, StartUpInstallation) {
Giovanni Ortuño Urquidi77b5bf72018-08-23 06:43:296670 extensions::TestExtensionRegistryObserver observer(
6671 extensions::ExtensionRegistry::Get(browser()->profile()));
6672 const extensions::Extension* installed_extension =
6673 observer.WaitForExtensionWillBeInstalled();
6674
6675 ASSERT_TRUE(installed_extension);
6676 const GURL installed_app_url =
6677 extensions::AppLaunchInfo::GetFullLaunchURL(installed_extension);
6678 EXPECT_EQ(policy_app_url_, installed_app_url);
6679}
6680
John Abd-El-Malek27b3ebd22019-02-12 18:59:186681#if defined(OS_WIN)
6682
6683class ForceNetworkInProcessTest : public InProcessBrowserTest {
6684 public:
6685 // InProcessBrowserTest implementation:
6686 void SetUp() override {
6687 EXPECT_CALL(policy_provider_, IsInitializationComplete(testing::_))
6688 .WillRepeatedly(testing::Return(true));
6689 policy::PolicyMap values;
6690 values.Set(policy::key::kForceNetworkInProcess,
6691 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
6692 policy::POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(true),
6693 nullptr);
6694 policy_provider_.UpdateChromePolicy(values);
6695 policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
6696 &policy_provider_);
6697
6698 InProcessBrowserTest::SetUp();
6699 }
6700
6701 private:
6702 policy::MockConfigurationPolicyProvider policy_provider_;
6703};
6704
6705IN_PROC_BROWSER_TEST_F(ForceNetworkInProcessTest, Enabled) {
John Abd-El-Malek27b3ebd22019-02-12 18:59:186706 ASSERT_TRUE(content::IsInProcessNetworkService());
6707}
6708
6709#endif // defined(OS_WIN)
6710
Elad Alonef479432018-08-27 10:43:576711#if !defined(OS_ANDROID)
Greg Thompson146eef8c2018-06-26 09:30:546712
6713// The possibilities for a boolean policy.
6714enum class BooleanPolicy {
6715 kNotConfigured,
6716 kFalse,
6717 kTrue,
6718};
6719
Elad Alonef479432018-08-27 10:43:576720#endif // !defined(OS_ANDROID)
6721
6722#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
6723
Greg Thompson146eef8c2018-06-26 09:30:546724// Tests that the PromotionalTabsEnabled policy properly suppresses the welcome
6725// page for browser first-runs.
6726class PromotionalTabsEnabledPolicyTest
6727 : public PolicyTest,
6728 public testing::WithParamInterface<BooleanPolicy> {
6729 protected:
Hector Carmona1e62e352019-06-24 19:18:176730 PromotionalTabsEnabledPolicyTest() {
6731 scoped_feature_list_.InitWithFeatures({nux::kNuxOnboardingForceEnabled},
6732 {});
6733 }
Greg Thompson146eef8c2018-06-26 09:30:546734 ~PromotionalTabsEnabledPolicyTest() = default;
6735
6736 void SetUp() override {
6737 // Ordinarily, browser tests include chrome://blank on the command line to
6738 // suppress any onboarding or promotional tabs. This test, on the other
6739 // hand, must evaluate startup with nothing on the command line so that a
6740 // default launch takes place.
6741 set_open_about_blank_on_browser_launch(false);
6742 PolicyTest::SetUp();
6743 }
6744
6745 void SetUpCommandLine(base::CommandLine* command_line) override {
6746 command_line->AppendSwitch(switches::kForceFirstRun);
6747 }
6748
6749 void CreatedBrowserMainParts(
6750 content::BrowserMainParts* browser_main_parts) override {
Greg Thompson5cd9ed312018-07-23 13:40:486751 // Set policies before the browser starts up.
6752 PolicyMap policies;
6753
6754 // Suppress the first-run dialog by disabling metrics reporting.
6755 policies.Set(key::kMetricsReportingEnabled, POLICY_LEVEL_MANDATORY,
6756 POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
6757 std::make_unique<base::Value>(false), nullptr);
6758
6759 // Apply the policy setting under test.
Greg Thompson146eef8c2018-06-26 09:30:546760 if (GetParam() != BooleanPolicy::kNotConfigured) {
Greg Thompson146eef8c2018-06-26 09:30:546761 policies.Set(
6762 key::kPromotionalTabsEnabled, POLICY_LEVEL_MANDATORY,
6763 POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
6764 std::make_unique<base::Value>(GetParam() == BooleanPolicy::kTrue),
6765 nullptr);
Greg Thompson146eef8c2018-06-26 09:30:546766 }
Greg Thompson5cd9ed312018-07-23 13:40:486767
6768 UpdateProviderPolicy(policies);
Greg Thompson146eef8c2018-06-26 09:30:546769 PolicyTest::CreatedBrowserMainParts(browser_main_parts);
6770 }
6771
6772 private:
Hector Carmona1e62e352019-06-24 19:18:176773 base::test::ScopedFeatureList scoped_feature_list_;
6774
Greg Thompson146eef8c2018-06-26 09:30:546775 DISALLOW_COPY_AND_ASSIGN(PromotionalTabsEnabledPolicyTest);
6776};
6777
Greg Thompson5cd9ed312018-07-23 13:40:486778IN_PROC_BROWSER_TEST_P(PromotionalTabsEnabledPolicyTest, RunTest) {
Greg Thompson146eef8c2018-06-26 09:30:546779 TabStripModel* tab_strip = browser()->tab_strip_model();
6780 ASSERT_GE(tab_strip->count(), 1);
6781 const auto& url = tab_strip->GetWebContentsAt(0)->GetURL();
6782 switch (GetParam()) {
6783 case BooleanPolicy::kFalse:
6784 // Only the NTP should show.
6785 EXPECT_EQ(tab_strip->count(), 1);
6786 if (url.possibly_invalid_spec() != chrome::kChromeUINewTabURL)
Kyle Milkae0f52502019-04-17 00:24:086787 EXPECT_TRUE(search::IsNTPOrRelatedURL(url, browser()->profile()))
6788 << url;
Greg Thompson146eef8c2018-06-26 09:30:546789 break;
6790 case BooleanPolicy::kNotConfigured:
6791 case BooleanPolicy::kTrue:
6792 // One or more onboarding tabs should show.
6793 EXPECT_NE(url.possibly_invalid_spec(), chrome::kChromeUINewTabURL);
Kyle Milkae0f52502019-04-17 00:24:086794 EXPECT_FALSE(search::IsNTPOrRelatedURL(url, browser()->profile())) << url;
Greg Thompson146eef8c2018-06-26 09:30:546795 break;
6796 }
6797}
Greg Thompsona37b35b2018-06-29 11:35:446798#undef MAYBE_RunTest
Greg Thompson146eef8c2018-06-26 09:30:546799
Victor Costane5e91512019-02-13 08:24:026800INSTANTIATE_TEST_SUITE_P(,
6801 PromotionalTabsEnabledPolicyTest,
6802 ::testing::Values(BooleanPolicy::kNotConfigured,
6803 BooleanPolicy::kFalse,
6804 BooleanPolicy::kTrue));
Greg Thompson146eef8c2018-06-26 09:30:546805
Elad Alonef479432018-08-27 10:43:576806#endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
6807
6808#if !defined(OS_ANDROID)
Elad Alon6bd69cb2018-08-06 18:20:456809class WebRtcEventLogCollectionAllowedPolicyTest
6810 : public PolicyTest,
6811 public testing::WithParamInterface<BooleanPolicy> {
6812 public:
6813 ~WebRtcEventLogCollectionAllowedPolicyTest() override = default;
6814
6815 void SetUpInProcessBrowserTestFixture() override {
6816 PolicyTest::SetUpInProcessBrowserTestFixture();
6817 PolicyMap policies;
6818
6819 const BooleanPolicy policy = GetParam();
6820 if (policy == BooleanPolicy::kFalse || policy == BooleanPolicy::kTrue) {
6821 const bool policy_bool = (policy == BooleanPolicy::kTrue);
6822 policies.Set(policy::key::kWebRtcEventLogCollectionAllowed,
6823 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
6824 policy::POLICY_SOURCE_ENTERPRISE_DEFAULT,
6825 std::make_unique<base::Value>(policy_bool), nullptr);
6826 }
6827
6828 provider_.UpdateChromePolicy(policies);
6829 }
6830
6831 const PrefService::Preference* GetPreference() const {
6832 auto* service = user_prefs::UserPrefs::Get(browser()->profile());
6833 return service->FindPreference(prefs::kWebRtcEventLogCollectionAllowed);
6834 }
6835
6836 base::OnceCallback<void(bool)> BlockingBoolExpectingReply(
6837 base::RunLoop* run_loop,
6838 bool expected_value) {
6839 return base::BindOnce(
6840 [](base::RunLoop* run_loop, bool expected_value, bool value) {
6841 EXPECT_EQ(expected_value, value);
6842 run_loop->Quit();
6843 },
6844 run_loop, expected_value);
6845 }
6846
6847 // The "extras" in question are the ID and error (only one of which may
6848 // be non-null), which this test ignores (tested elsewhere).
6849 base::OnceCallback<void(bool, const std::string&, const std::string&)>
6850 BlockingBoolExpectingReplyWithExtras(base::RunLoop* run_loop,
6851 bool expected_value) {
6852 return base::BindOnce(
6853 [](base::RunLoop* run_loop, bool expected_value, bool value,
6854 const std::string& ignored_log_id,
6855 const std::string& ignored_error) {
6856 EXPECT_EQ(expected_value, value);
6857 run_loop->Quit();
6858 },
6859 run_loop, expected_value);
6860 }
6861};
6862
6863IN_PROC_BROWSER_TEST_P(WebRtcEventLogCollectionAllowedPolicyTest, RunTest) {
6864 const PrefService::Preference* const pref = GetPreference();
6865 const bool remote_logging_allowed = (GetParam() == BooleanPolicy::kTrue);
6866 ASSERT_EQ(pref->GetValue()->GetBool(), remote_logging_allowed);
6867
6868 auto* webrtc_event_log_manager = WebRtcEventLogManager::GetInstance();
6869 ASSERT_TRUE(webrtc_event_log_manager);
6870
6871 content::WebContents* web_contents =
6872 browser()->tab_strip_model()->GetActiveWebContents();
6873 int render_process_id = web_contents->GetMainFrame()->GetProcess()->GetID();
6874
6875 constexpr int kLid = 123;
Elad Alon5b9d29d2019-03-01 22:28:296876 const std::string kSessionId = "id";
Elad Alon6bd69cb2018-08-06 18:20:456877
6878 {
6879 base::RunLoop run_loop;
6880 webrtc_event_log_manager->PeerConnectionAdded(
Elad Alon5b9d29d2019-03-01 22:28:296881 render_process_id, kLid, BlockingBoolExpectingReply(&run_loop, true));
6882 run_loop.Run();
6883 }
6884
6885 {
6886 base::RunLoop run_loop;
6887 webrtc_event_log_manager->PeerConnectionSessionIdSet(
6888 render_process_id, kLid, kSessionId,
Elad Alon6bd69cb2018-08-06 18:20:456889 BlockingBoolExpectingReply(&run_loop, true));
6890 run_loop.Run();
6891 }
6892
6893 {
6894 constexpr size_t kMaxFileSizeBytes = 1000 * 1000;
Elad Alona085b1d2018-12-08 23:55:586895 constexpr int kOutputPeriodMs = 1000;
6896
Elad Alon6bd69cb2018-08-06 18:20:456897 base::RunLoop run_loop;
6898
6899 // Test focus - remote-bound logging allowed if and only if the policy
6900 // is configured to allow it.
6901 webrtc_event_log_manager->StartRemoteLogging(
Elad Alon5b9d29d2019-03-01 22:28:296902 render_process_id, kSessionId, kMaxFileSizeBytes, kOutputPeriodMs,
6903 kWebAppId,
Elad Alon6bd69cb2018-08-06 18:20:456904 BlockingBoolExpectingReplyWithExtras(&run_loop,
6905 remote_logging_allowed));
6906 run_loop.Run();
6907 }
6908}
6909
Victor Costane5e91512019-02-13 08:24:026910INSTANTIATE_TEST_SUITE_P(,
6911 WebRtcEventLogCollectionAllowedPolicyTest,
6912 ::testing::Values(BooleanPolicy::kNotConfigured,
6913 BooleanPolicy::kFalse,
6914 BooleanPolicy::kTrue));
Elad Alonef479432018-08-27 10:43:576915#endif // !defined(OS_ANDROID)
Greg Thompson146eef8c2018-06-26 09:30:546916
Kunihiko Sakamotof586da62019-03-28 03:03:046917class SignedExchangePolicyTest : public PolicyTest {
6918 public:
6919 SignedExchangePolicyTest() {}
6920 ~SignedExchangePolicyTest() override {}
6921
6922 void SetUp() override {
6923 embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
6924 embedded_test_server()->RegisterRequestMonitor(base::BindRepeating(
6925 &SignedExchangePolicyTest::MonitorRequest, base::Unretained(this)));
6926 ASSERT_TRUE(embedded_test_server()->Start());
6927
6928 sxg_test_helper_.SetUp();
6929 PolicyTest::SetUp();
6930 }
6931
6932 void TearDownOnMainThread() override {
6933 PolicyTest::TearDownOnMainThread();
6934 sxg_test_helper_.TearDownOnMainThread();
6935 }
6936
6937 protected:
6938 void SetSignedExchangePolicy(bool enabled) {
6939 PolicyMap policies;
6940 policies.Set(key::kSignedHTTPExchangeEnabled, POLICY_LEVEL_MANDATORY,
6941 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
6942 std::make_unique<base::Value>(enabled), nullptr);
6943 UpdateProviderPolicy(policies);
6944 }
6945
6946 void InstallUrlInterceptor(const GURL& url, const std::string& data_path) {
6947 sxg_test_helper_.InstallUrlInterceptor(url, data_path);
6948 }
6949
6950 bool HadSignedExchangeInAcceptHeader(const GURL& url) const {
6951 const auto it = url_accept_header_map_.find(url);
6952 if (it == url_accept_header_map_.end())
6953 return false;
6954 return it->second.find("application/signed-exchange") != std::string::npos;
6955 }
6956
6957 private:
6958 void MonitorRequest(const net::test_server::HttpRequest& request) {
6959 const auto it = request.headers.find("Accept");
6960 if (it == request.headers.end())
6961 return;
6962 url_accept_header_map_[request.base_url.Resolve(request.relative_url)] =
6963 it->second;
6964 }
6965
6966 content::SignedExchangeBrowserTestHelper sxg_test_helper_;
6967 std::map<GURL, std::string> url_accept_header_map_;
6968};
6969
6970IN_PROC_BROWSER_TEST_F(SignedExchangePolicyTest, SignedExchangeDisabled) {
6971 SetSignedExchangePolicy(false);
6972
6973 content::DownloadTestObserverTerminal download_observer(
6974 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
6975 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
6976
6977 GURL url = embedded_test_server()->GetURL("/sxg/test.example.org_test.sxg");
6978 ui_test_utils::NavigateToURL(browser(), url);
6979
6980 download_observer.WaitForFinished();
6981
6982 // Check that the SXG file was not loaded as a page, but downloaded.
6983 std::vector<download::DownloadItem*> downloads;
6984 content::BrowserContext::GetDownloadManager(browser()->profile())
6985 ->GetAllDownloads(&downloads);
6986 ASSERT_EQ(1u, downloads.size());
6987 EXPECT_EQ(downloads[0]->GetURL(), url);
6988
6989 ASSERT_FALSE(HadSignedExchangeInAcceptHeader(url));
6990}
6991
6992IN_PROC_BROWSER_TEST_F(SignedExchangePolicyTest, SignedExchangeEnabled) {
6993 SetSignedExchangePolicy(true);
6994
6995 InstallUrlInterceptor(GURL("https://test.example.org/test/"),
6996 "content/test/data/sxg/fallback.html");
6997
6998 GURL url = embedded_test_server()->GetURL("/sxg/test.example.org_test.sxg");
6999 base::string16 title = base::ASCIIToUTF16("Fallback URL response");
7000 content::TitleWatcher title_watcher(
7001 browser()->tab_strip_model()->GetActiveWebContents(), title);
7002 ui_test_utils::NavigateToURL(browser(), url);
7003
7004 // Check that the SXG file was handled as a Signed Exchange, and the
7005 // navigation was redirected to the SXG's fallback URL.
7006 EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
7007
7008 ASSERT_TRUE(HadSignedExchangeInAcceptHeader(url));
7009}
7010
[email protected]3757c7d2012-07-23 11:24:367011} // namespace policy