diff options
author | joaodasilva@chromium.org <joaodasilva@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-12-08 21:10:04 +0000 |
---|---|---|
committer | joaodasilva@chromium.org <joaodasilva@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-12-08 21:10:04 +0000 |
commit | 76b4b15804dafa5e586738bd7c8ac12fea6ddec2 (patch) | |
tree | 4ba2cb5383bb9ef5f610aeffe5d4455149da683b /chrome | |
parent | 415b2de91f4a96c6779650c2a94e28012c7d61e7 (diff) | |
download | chromium_src-76b4b15804dafa5e586738bd7c8ac12fea6ddec2.zip chromium_src-76b4b15804dafa5e586738bd7c8ac12fea6ddec2.tar.gz chromium_src-76b4b15804dafa5e586738bd7c8ac12fea6ddec2.tar.bz2 |
Move policy code into components/policy.
The code moved to component/policy can be included on iOS, but can't depend
on chrome/. This move includes an exception for the policy protobufs:
- the generic cloud policy protobufs will be moved into a new repository,
due to a dependency from a ChromeOS package
- the user cloud policy protobuf and its decoding will move into a new component
for user policy
BUG=271392
TBR=jochen@chromium.org
Review URL: https://codereview.chromium.org/109743002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239399 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome')
257 files changed, 351 insertions, 21592 deletions
diff --git a/chrome/browser/android/signin/signin_manager_android.cc b/chrome/browser/android/signin/signin_manager_android.cc index 295900d..3c9fa44 100644 --- a/chrome/browser/android/signin/signin_manager_android.cc +++ b/chrome/browser/android/signin/signin_manager_android.cc @@ -29,12 +29,12 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_android.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "google_apis/gaia/gaia_auth_util.h" #endif diff --git a/chrome/browser/automation/testing_automation_provider.cc b/chrome/browser/automation/testing_automation_provider.cc index 1c4a35f..527dd71 100644 --- a/chrome/browser/automation/testing_automation_provider.cc +++ b/chrome/browser/automation/testing_automation_provider.cc @@ -152,7 +152,7 @@ #include "ui/events/keycodes/keyboard_codes.h" #if defined(ENABLE_CONFIGURATION_POLICY) -#include "chrome/browser/policy/policy_service.h" +#include "components/policy/core/common/policy_service.h" #endif #if defined(OS_CHROMEOS) diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 09e20ef..74597c3 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc @@ -53,7 +53,6 @@ #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/plugins/chrome_plugin_service_filter.h" #include "chrome/browser/plugins/plugin_finder.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/prefs/chrome_pref_service_factory.h" #include "chrome/browser/prerender/prerender_tracker.h" @@ -79,6 +78,7 @@ #include "chrome/common/switch_utils.h" #include "chrome/common/url_constants.h" #include "chrome/installer/util/google_update_constants.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/notification_details.h" @@ -94,7 +94,7 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" #else -#include "chrome/browser/policy/policy_service_stub.h" +#include "components/policy/core/common/policy_service_stub.h" #endif // defined(ENABLE_CONFIGURATION_POLICY) #if defined(OS_WIN) diff --git a/chrome/browser/chromeos/attestation/attestation_policy_observer.cc b/chrome/browser/chromeos/attestation/attestation_policy_observer.cc index 9aab264..ee8d5de 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_observer.cc +++ b/chrome/browser/chromeos/attestation/attestation_policy_observer.cc @@ -14,13 +14,13 @@ #include "chrome/browser/chromeos/attestation/attestation_ca_client.h" #include "chrome/browser/chromeos/attestation/attestation_key_payload.pb.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" #include "chromeos/attestation/attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "net/cert/x509_certificate.h" @@ -269,7 +269,7 @@ void AttestationPolicyObserver::GetKeyPayload( void AttestationPolicyObserver::OnUploadComplete(bool status) { if (!status) return; - LOG(INFO) << "Enterprise Machine Certificate uploaded to DMServer."; + VLOG(1) << "Enterprise Machine Certificate uploaded to DMServer."; GetKeyPayload(base::Bind(&AttestationPolicyObserver::MarkAsUploaded, weak_factory_.GetWeakPtr())); } diff --git a/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc b/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc index 3e06b1a..1268d10 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc +++ b/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc @@ -12,10 +12,10 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" #include "chromeos/attestation/mock_attestation_flow.h" #include "chromeos/dbus/mock_cryptohome_client.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "content/public/test/test_browser_thread.h" #include "crypto/rsa_private_key.h" #include "net/cert/x509_certificate.h" diff --git a/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h b/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h index c9abf5d..6b5f71a 100644 --- a/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h +++ b/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h @@ -14,7 +14,7 @@ #include "base/sequenced_task_runner.h" #include "chrome/browser/chromeos/extensions/external_cache.h" #include "chrome/browser/extensions/external_loader.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" namespace chromeos { diff --git a/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader_unittest.cc b/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader_unittest.cc index 9f30f7a..e7c2cc7 100644 --- a/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader_unittest.cc +++ b/chrome/browser/chromeos/extensions/device_local_account_external_policy_loader_unittest.cc @@ -19,10 +19,10 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/external_provider_impl.h" #include "chrome/browser/extensions/updater/extension_downloader.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/test/base/testing_browser_process.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" #include "content/public/browser/notification_service.h" diff --git a/chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.cc b/chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.cc index 569e143..7734998 100644 --- a/chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.cc +++ b/chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.cc @@ -15,9 +15,9 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chromeos/chromeos_switches.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "content/public/browser/browser_thread.h" namespace chromeos { diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc index b08ec37..350d3be 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc @@ -17,11 +17,11 @@ #include "chrome/browser/chromeos/policy/auto_enrollment_client.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/enterprise_metrics.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" +#include "components/policy/core/common/cloud/enterprise_metrics.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/google_service_auth_error.h" diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen.h b/chrome/browser/chromeos/login/enrollment/enrollment_screen.h index 0db7475..97388826 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen.h +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen.h @@ -12,7 +12,7 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/login/enrollment/enrollment_screen_actor.h" #include "chrome/browser/chromeos/login/screens/wizard_screen.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace chromeos { diff --git a/chrome/browser/chromeos/login/existing_user_controller.cc b/chrome/browser/chromeos/login/existing_user_controller.cc index b18fbac..443373e 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.cc +++ b/chrome/browser/chromeos/login/existing_user_controller.cc @@ -37,7 +37,6 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/google/google_util.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" @@ -48,6 +47,7 @@ #include "chromeos/dbus/power_manager_client.h" #include "chromeos/dbus/session_manager_client.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" @@ -257,7 +257,7 @@ void ExistingUserController::Observe( // just after the UI is closed but before the new credentials were stored // in the profile. Therefore we have to give it some time to make sure it // has been updated before we copy it. - LOG(INFO) << "Authentication was entered manually, possibly for proxyauth."; + VLOG(1) << "Authentication was entered manually, possibly for proxyauth."; scoped_refptr<net::URLRequestContextGetter> browser_process_context_getter = g_browser_process->system_request_context(); Profile* signin_profile = ProfileHelper::GetSigninProfile(); diff --git a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc index 96dfe3a..c5137bb 100644 --- a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc @@ -28,11 +28,6 @@ #include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/testing_browser_process.h" @@ -41,6 +36,11 @@ #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/fake_session_manager_client.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "content/public/test/mock_notification_observer.h" #include "content/public/test/test_utils.h" #include "google_apis/gaia/mock_url_fetcher_factory.h" diff --git a/chrome/browser/chromeos/login/kiosk_browsertest.cc b/chrome/browser/chromeos/login/kiosk_browsertest.cc index 0189bf1..e66f578 100644 --- a/chrome/browser/chromeos/login/kiosk_browsertest.cc +++ b/chrome/browser/chromeos/login/kiosk_browsertest.cc @@ -42,7 +42,6 @@ #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/lifetime/application_lifetime.h" -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" @@ -56,6 +55,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "chromeos/chromeos_switches.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" diff --git a/chrome/browser/chromeos/login/login_utils_browsertest.cc b/chrome/browser/chromeos/login/login_utils_browsertest.cc index 14e423f..0b6365d 100644 --- a/chrome/browser/chromeos/login/login_utils_browsertest.cc +++ b/chrome/browser/chromeos/login/login_utils_browsertest.cc @@ -30,8 +30,6 @@ #include "chrome/browser/io_thread.h" #include "chrome/browser/net/predictor.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h" #include "chrome/browser/profiles/profile_manager.h" @@ -51,6 +49,8 @@ #include "chromeos/network/network_handler.h" #include "chromeos/system/mock_statistics_provider.h" #include "chromeos/system/statistics_provider.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread.h" #include "content/public/test/test_utils.h" diff --git a/chrome/browser/chromeos/login/screens/user_image_screen.cc b/chrome/browser/chromeos/login/screens/user_image_screen.cc index ebe2fe1..a7a4995 100644 --- a/chrome/browser/chromeos/login/screens/user_image_screen.cc +++ b/chrome/browser/chromeos/login/screens/user_image_screen.cc @@ -25,13 +25,13 @@ #include "chrome/browser/chromeos/login/user_image_manager.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/login/wizard_controller.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "grit/generated_resources.h" diff --git a/chrome/browser/chromeos/login/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/user_image_manager_browsertest.cc index a1b8f1d..4c1cd24 100644 --- a/chrome/browser/chromeos/login/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/user_image_manager_browsertest.cc @@ -38,9 +38,6 @@ #include "chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_downloader.h" #include "chrome/common/chrome_paths.h" @@ -52,6 +49,9 @@ #include "chromeos/dbus/fake_dbus_thread_manager.h" #include "chromeos/dbus/fake_session_manager_client.h" #include "chromeos/dbus/session_manager_client.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/test/test_utils.h" diff --git a/chrome/browser/chromeos/login/version_info_updater.h b/chrome/browser/chromeos/login/version_info_updater.h index becce6b..bde2594 100644 --- a/chrome/browser/chromeos/login/version_info_updater.h +++ b/chrome/browser/chromeos/login/version_info_updater.h @@ -12,7 +12,7 @@ #include "chrome/browser/chromeos/boot_times_loader.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/version_loader.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" namespace chromeos { diff --git a/chrome/browser/chromeos/policy/auto_enrollment_client.cc b/chrome/browser/chromeos/policy/auto_enrollment_client.cc index ba13f75..a0fbc2b 100644 --- a/chrome/browser/chromeos/policy/auto_enrollment_client.cc +++ b/chrome/browser/chromeos/policy/auto_enrollment_client.cc @@ -18,10 +18,10 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/system_policy_request_context.h" #include "chrome/common/pref_names.h" #include "chromeos/chromeos_switches.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/system_policy_request_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_client.h" #include "crypto/sha2.h" diff --git a/chrome/browser/chromeos/policy/auto_enrollment_client.h b/chrome/browser/chromeos/policy/auto_enrollment_client.h index cac0f68..6d6b877 100644 --- a/chrome/browser/chromeos/policy/auto_enrollment_client.h +++ b/chrome/browser/chromeos/policy/auto_enrollment_client.h @@ -12,7 +12,7 @@ #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "base/time/time.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "net/base/network_change_notifier.h" #include "third_party/protobuf/src/google/protobuf/repeated_field.h" diff --git a/chrome/browser/chromeos/policy/auto_enrollment_client_unittest.cc b/chrome/browser/chromeos/policy/auto_enrollment_client_unittest.cc index be1be30..a2f343f 100644 --- a/chrome/browser/chromeos/policy/auto_enrollment_client_unittest.cc +++ b/chrome/browser/chromeos/policy/auto_enrollment_client_unittest.cc @@ -11,10 +11,10 @@ #include "base/prefs/testing_pref_service.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" +#include "components/policy/core/common/cloud/mock_device_management_service.h" #include "content/public/test/test_browser_thread_bundle.h" #include "crypto/sha2.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc b/chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc index 53f68c0..3fcc6b2 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc @@ -18,9 +18,9 @@ #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "chrome/browser/chromeos/policy/cloud_external_data_store.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" -#include "chrome/browser/policy/cloud/external_policy_data_updater.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/external_policy_data_fetcher.h" +#include "components/policy/core/common/cloud/external_policy_data_updater.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/chromeos/policy/cloud_external_data_manager_base.h b/chrome/browser/chromeos/policy/cloud_external_data_manager_base.h index 96c80da..dc82ca6 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_manager_base.h +++ b/chrome/browser/chromeos/policy/cloud_external_data_manager_base.h @@ -10,7 +10,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/policy_details.h" namespace base { diff --git a/chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.cc b/chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.cc index 2382293..4fa6368 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.cc @@ -9,9 +9,9 @@ #include "base/sha1.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" diff --git a/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc b/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc index 3618e82..8636f2fa 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_manager_base_unittest.cc @@ -19,11 +19,11 @@ #include "base/test/test_simple_task_runner.h" #include "base/values.h" #include "chrome/browser/chromeos/policy/cloud_external_data_store.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/resource_cache.h" -#include "chrome/browser/policy/test/policy_test_utils.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" +#include "components/policy/core/common/cloud/resource_cache.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_test_utils.h" #include "components/policy/core/common/policy_types.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" diff --git a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer.cc b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer.cc index 12b974c..437c9a6 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer.cc @@ -16,16 +16,16 @@ #include "chrome/browser/chromeos/login/user.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/policy/device_local_account.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/settings/cros_settings_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_namespace.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" diff --git a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc index c7edbde..1f0464b 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_policy_observer_unittest.cc @@ -25,19 +25,19 @@ #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/mock_cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "chrome/browser/policy/policy_service.h" -#include "chrome/browser/policy/policy_service_impl.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/testing_profile.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service.h" +#include "components/policy/core/common/policy_service_impl.h" #include "components/policy/core/common/policy_types.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" diff --git a/chrome/browser/chromeos/policy/cloud_external_data_store.cc b/chrome/browser/chromeos/policy/cloud_external_data_store.cc index a00cd8a..d19c2a9 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_store.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_store.cc @@ -10,7 +10,7 @@ #include "base/sequenced_task_runner.h" #include "base/sha1.h" #include "base/strings/string_number_conversions.h" -#include "chrome/browser/policy/cloud/resource_cache.h" +#include "components/policy/core/common/cloud/resource_cache.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/cloud_external_data_store.h b/chrome/browser/chromeos/policy/cloud_external_data_store.h index 079a0db..8f229f5 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_store.h +++ b/chrome/browser/chromeos/policy/cloud_external_data_store.h @@ -9,7 +9,7 @@ #include "base/basictypes.h" #include "base/memory/ref_counted.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/cloud_external_data_store_unittest.cc b/chrome/browser/chromeos/policy/cloud_external_data_store_unittest.cc index 29bafee..d8333301 100644 --- a/chrome/browser/chromeos/policy/cloud_external_data_store_unittest.cc +++ b/chrome/browser/chromeos/policy/cloud_external_data_store_unittest.cc @@ -9,7 +9,7 @@ #include "base/memory/scoped_ptr.h" #include "base/sha1.h" #include "base/test/test_simple_task_runner.h" -#include "chrome/browser/policy/cloud/resource_cache.h" +#include "components/policy/core/common/cloud/resource_cache.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/configuration_policy_handler_chromeos.h b/chrome/browser/chromeos/policy/configuration_policy_handler_chromeos.h index a756a83..7ec6081 100644 --- a/chrome/browser/chromeos/policy/configuration_policy_handler_chromeos.h +++ b/chrome/browser/chromeos/policy/configuration_policy_handler_chromeos.h @@ -8,9 +8,9 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "chrome/browser/extensions/policy_handlers.h" -#include "chrome/browser/policy/configuration_policy_handler.h" #include "chromeos/network/network_ui_data.h" #include "components/onc/onc_constants.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace base { class DictionaryValue; diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc index 1dbbd93..390e874 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.cc @@ -14,14 +14,14 @@ #include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h" #include "chrome/browser/chromeos/policy/enrollment_handler_chromeos.h" #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/system_policy_request_context.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/common/pref_names.h" #include "chromeos/chromeos_constants.h" #include "chromeos/system/statistics_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/system_policy_request_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_client.h" #include "url/gurl.h" diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h index 1208478..ec1fc04 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h @@ -14,9 +14,9 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc index bcf2e40..ce229a1 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc @@ -18,8 +18,6 @@ #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/browser/prefs/browser_prefs.h" @@ -29,6 +27,8 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/system/mock_statistics_provider.h" #include "chromeos/system/statistics_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/mock_device_management_service.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/schema_registry.h" #include "google_apis/gaia/gaia_oauth_client.h" diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h b/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h index 6afcd44..cb9c78ab 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h +++ b/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h @@ -12,7 +12,7 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_validator.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_validator.h b/chrome/browser/chromeos/policy/device_cloud_policy_validator.h index f4ab747..b4b301d 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_validator.h +++ b/chrome/browser/chromeos/policy/device_cloud_policy_validator.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_CLOUD_POLICY_VALIDATOR_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_CLOUD_POLICY_VALIDATOR_H_ -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" namespace enterprise_management { class ChromeDeviceSettingsProto; diff --git a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc index 43d1758..e2ec50e 100644 --- a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc @@ -53,11 +53,6 @@ #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" @@ -79,9 +74,14 @@ #include "chromeos/chromeos_paths.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/fake_session_manager_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/web_contents.h" diff --git a/chrome/browser/chromeos/policy/device_local_account_external_data_manager.cc b/chrome/browser/chromeos/policy/device_local_account_external_data_manager.cc index 8d43bc7..44dd4e6 100644 --- a/chrome/browser/chromeos/policy/device_local_account_external_data_manager.cc +++ b/chrome/browser/chromeos/policy/device_local_account_external_data_manager.cc @@ -8,7 +8,7 @@ #include "base/sequenced_task_runner.h" #include "chrome/browser/chromeos/policy/cloud_external_data_store.h" #include "chrome/browser/chromeos/policy/device_local_account_external_data_service.h" -#include "chrome/browser/policy/cloud/resource_cache.h" +#include "components/policy/core/common/cloud/resource_cache.h" #include "policy/policy_constants.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/device_local_account_external_data_service.cc b/chrome/browser/chromeos/policy/device_local_account_external_data_service.cc index 6162540..9bc0f72 100644 --- a/chrome/browser/chromeos/policy/device_local_account_external_data_service.cc +++ b/chrome/browser/chromeos/policy/device_local_account_external_data_service.cc @@ -13,8 +13,8 @@ #include "base/logging.h" #include "base/path_service.h" #include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" #include "chromeos/chromeos_paths.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "policy/policy_constants.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/device_local_account_external_data_service.h b/chrome/browser/chromeos/policy/device_local_account_external_data_service.h index 01db340..2174ef8 100644 --- a/chrome/browser/chromeos/policy/device_local_account_external_data_service.h +++ b/chrome/browser/chromeos/policy/device_local_account_external_data_service.h @@ -14,7 +14,7 @@ #include "base/memory/scoped_ptr.h" #include "chrome/browser/chromeos/policy/device_local_account_external_data_manager.h" #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h" -#include "chrome/browser/policy/cloud/resource_cache.h" +#include "components/policy/core/common/cloud/resource_cache.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_provider.cc b/chrome/browser/chromeos/policy/device_local_account_policy_provider.cc index ddd9726..dafac17 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_provider.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_provider.cc @@ -6,8 +6,8 @@ #include "base/bind.h" #include "chrome/browser/chromeos/policy/device_local_account_external_data_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" #include "components/policy/core/common/policy_bundle.h" #include "components/policy/core/common/policy_namespace.h" diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_service.cc b/chrome/browser/chromeos/policy/device_local_account_policy_service.cc index f596c67..6d8d828 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_service.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_service.cc @@ -21,16 +21,16 @@ #include "chrome/browser/chromeos/policy/device_local_account_external_data_service.h" #include "chrome/browser/chromeos/policy/device_local_account_policy_store.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/system_policy_request_context.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chromeos/chromeos_paths.h" #include "chromeos/dbus/session_manager_client.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/settings/cros_settings_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/system_policy_request_context.h" #include "content/public/common/content_client.h" #include "net/url_request/url_request_context_getter.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_service.h b/chrome/browser/chromeos/policy/device_local_account_policy_service.h index 767eb4b..2f9e776 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_service.h +++ b/chrome/browser/chromeos/policy/device_local_account_policy_service.h @@ -18,8 +18,8 @@ #include "chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h" #include "chrome/browser/chromeos/policy/device_local_account_external_data_manager.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_service_unittest.cc b/chrome/browser/chromeos/policy/device_local_account_policy_service_unittest.cc index 877fdb9..7aec9de 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_service_unittest.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_service_unittest.cc @@ -23,15 +23,15 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/common/chrome_paths.h" #include "chromeos/chromeos_paths.h" #include "chromeos/dbus/power_policy_controller.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" +#include "components/policy/core/common/cloud/mock_device_management_service.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/schema_registry.h" diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_store.cc b/chrome/browser/chromeos/policy/device_local_account_policy_store.cc index f5e013e..b25232b 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_store.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_store.cc @@ -7,10 +7,10 @@ #include "base/bind.h" #include "base/callback.h" #include "base/values.h" -#include "chrome/browser/policy/cloud/device_management_service.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chromeos/dbus/power_policy_controller.h" #include "chromeos/dbus/session_manager_client.h" +#include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_types.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_store.h b/chrome/browser/chromeos/policy/device_local_account_policy_store.h index 1929bd5..e8ac62e 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_store.h +++ b/chrome/browser/chromeos/policy/device_local_account_policy_store.h @@ -13,8 +13,8 @@ #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" #include "chrome/browser/policy/cloud/user_cloud_policy_store_base.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/device_policy_builder.cc b/chrome/browser/chromeos/policy/device_policy_builder.cc index eebc704..0d70d70 100644 --- a/chrome/browser/chromeos/policy/device_policy_builder.cc +++ b/chrome/browser/chromeos/policy/device_policy_builder.cc @@ -4,8 +4,8 @@ #include "chrome/browser/chromeos/policy/device_policy_builder.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace em = enterprise_management; diff --git a/chrome/browser/chromeos/policy/device_policy_builder.h b/chrome/browser/chromeos/policy/device_policy_builder.h index c4bf0d24c..7b21b88 100644 --- a/chrome/browser/chromeos/policy/device_policy_builder.h +++ b/chrome/browser/chromeos/policy/device_policy_builder.h @@ -5,8 +5,8 @@ #ifndef CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_POLICY_BUILDER_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_POLICY_BUILDER_H_ -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" +#include "components/policy/core/common/cloud/policy_builder.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/device_status_collector.cc b/chrome/browser/chromeos/policy/device_status_collector.cc index b275e1f..5de8029 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/device_status_collector.cc @@ -22,7 +22,6 @@ #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" @@ -32,6 +31,7 @@ #include "chromeos/network/network_state_handler.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/system/statistics_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "content/public/browser/browser_thread.h" #include "third_party/cros_system_api/dbus/service_constants.h" diff --git a/chrome/browser/chromeos/policy/device_status_collector.h b/chrome/browser/chromeos/policy/device_status_collector.h index 6ee8df1..3f584c1 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.h +++ b/chrome/browser/chromeos/policy/device_status_collector.h @@ -18,8 +18,8 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/version_loader.h" #include "chrome/browser/idle.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" #include "chrome/common/cancelable_task_tracker.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" #include "content/public/browser/geolocation_provider.h" #include "content/public/common/geoposition.h" diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc index 0cbf646..768d155 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc @@ -12,10 +12,10 @@ #include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h" #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chromeos/chromeos_switches.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "net/http/http_status_code.h" diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h index 7730313..c15e146 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h @@ -15,8 +15,8 @@ #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_validator.h" #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "google_apis/gaia/gaia_oauth_client.h" namespace base { diff --git a/chrome/browser/chromeos/policy/enrollment_status_chromeos.h b/chrome/browser/chromeos/policy/enrollment_status_chromeos.h index 5845c86..f2c4281 100644 --- a/chrome/browser/chromeos/policy/enrollment_status_chromeos.h +++ b/chrome/browser/chromeos/policy/enrollment_status_chromeos.h @@ -5,9 +5,9 @@ #ifndef CHROME_BROWSER_CHROMEOS_POLICY_ENROLLMENT_STATUS_CHROMEOS_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_ENROLLMENT_STATUS_CHROMEOS_H_ -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/enterprise_install_attributes.h b/chrome/browser/chromeos/policy/enterprise_install_attributes.h index b4fb2c0..a8e46d3 100644 --- a/chrome/browser/chromeos/policy/enterprise_install_attributes.h +++ b/chrome/browser/chromeos/policy/enterprise_install_attributes.h @@ -13,9 +13,9 @@ #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/login_profile_policy_provider.h b/chrome/browser/chromeos/policy/login_profile_policy_provider.h index b9fbbd6..e8fbd91 100644 --- a/chrome/browser/chromeos/policy/login_profile_policy_provider.h +++ b/chrome/browser/chromeos/policy/login_profile_policy_provider.h @@ -8,8 +8,8 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/policy_service.h" #include "components/policy/core/common/configuration_policy_provider.h" +#include "components/policy/core/common/policy_service.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/login_screen_power_management_policy.cc b/chrome/browser/chromeos/policy/login_screen_power_management_policy.cc index 57a0cd9..2e8ce27 100644 --- a/chrome/browser/chromeos/policy/login_screen_power_management_policy.cc +++ b/chrome/browser/chromeos/policy/login_screen_power_management_policy.cc @@ -7,8 +7,8 @@ #include "base/json/json_reader.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" -#include "chrome/browser/policy/configuration_policy_handler.h" #include "chromeos/dbus/power_policy_controller.h" +#include "components/policy/core/browser/configuration_policy_handler.h" #include "components/policy/core/browser/policy_error_map.h" #include "grit/component_strings.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/chromeos/policy/network_configuration_updater.h b/chrome/browser/chromeos/policy/network_configuration_updater.h index 4b6556b..18cd350 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater.h +++ b/chrome/browser/chromeos/policy/network_configuration_updater.h @@ -10,8 +10,8 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/policy_service.h" #include "components/onc/onc_constants.h" +#include "components/policy/core/common/policy_service.h" namespace base { class DictionaryValue; diff --git a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc index dc33c1d..48d3172 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc +++ b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc @@ -11,7 +11,6 @@ #include "base/values.h" #include "chrome/browser/chromeos/login/user.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h" -#include "chrome/browser/policy/policy_service_impl.h" #include "chromeos/network/mock_managed_network_configuration_handler.h" #include "chromeos/network/onc/mock_certificate_importer.h" #include "chromeos/network/onc/onc_test_utils.h" @@ -20,6 +19,7 @@ #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service_impl.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "net/base/test_data_directory.h" diff --git a/chrome/browser/chromeos/policy/power_policy_browsertest.cc b/chrome/browser/chromeos/policy/power_policy_browsertest.cc index 451b99b..d3d6bfe 100644 --- a/chrome/browser/chromeos/policy/power_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/power_policy_browsertest.cc @@ -27,11 +27,6 @@ #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/extensions/api/power/power_api_manager.h" #include "chrome/browser/lifetime/application_lifetime.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "chrome/browser/policy/mock_policy_service.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" @@ -48,7 +43,12 @@ #include "chromeos/dbus/fake_session_manager_client.h" #include "chromeos/dbus/power_manager/policy.pb.h" #include "chromeos/dbus/power_policy_controller.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "components/policy/core/common/external_data_fetcher.h" +#include "components/policy/core/common/mock_policy_service.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" diff --git a/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc b/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc index 39516a1..5d67f7c 100644 --- a/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc +++ b/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc @@ -6,7 +6,7 @@ #include <string> -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h b/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h index 7c91f92..2ddccec 100644 --- a/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h +++ b/chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h @@ -9,7 +9,7 @@ #include "base/basictypes.h" #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/user_cloud_external_data_manager.cc b/chrome/browser/chromeos/policy/user_cloud_external_data_manager.cc index 39f859c..52a7eed 100644 --- a/chrome/browser/chromeos/policy/user_cloud_external_data_manager.cc +++ b/chrome/browser/chromeos/policy/user_cloud_external_data_manager.cc @@ -8,8 +8,8 @@ #include "base/memory/scoped_ptr.h" #include "base/sequenced_task_runner.h" #include "chrome/browser/chromeos/policy/cloud_external_data_store.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/resource_cache.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/resource_cache.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/user_cloud_external_data_manager_browsertest.cc b/chrome/browser/chromeos/policy/user_cloud_external_data_manager_browsertest.cc index 559e720..edca1fd 100644 --- a/chrome/browser/chromeos/policy/user_cloud_external_data_manager_browsertest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_external_data_manager_browsertest.cc @@ -16,16 +16,16 @@ #include "chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/test/test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc index 3b9110e..6b65dcb 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc @@ -14,10 +14,10 @@ #include "chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/system_policy_request_context.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/system_policy_request_context.h" #include "components/policy/core/common/policy_pref_names.h" #include "content/public/common/content_client.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h index f2bb796..d180a74 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h @@ -14,11 +14,11 @@ #include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" #include "components/browser_context_keyed_service/browser_context_keyed_service.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" class GoogleServiceAuthError; class PrefService; diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc index c217314..d0fdf3d 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos_unittest.cc @@ -17,10 +17,6 @@ #include "base/test/test_simple_task_runner.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/mock_cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/prefs/pref_service_syncable.h" @@ -31,6 +27,10 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" +#include "components/policy/core/common/cloud/mock_device_management_service.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/schema_registry.h" diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc index d852d7d..3e3f531 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc @@ -22,8 +22,6 @@ #include "chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/device_management_service.h" #include "chrome/browser/policy/schema_registry_service.h" #include "chrome/browser/policy/schema_registry_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -31,6 +29,8 @@ #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/device_management_service.h" #include "content/public/browser/browser_thread.h" #include "net/url_request/url_request_context_getter.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h index e1939f8..39696b48 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h @@ -14,9 +14,9 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" #include "chrome/browser/policy/cloud/user_cloud_policy_store_base.h" #include "chromeos/dbus/dbus_method_call_status.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc index 7f0694a..c766137 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc @@ -13,12 +13,12 @@ #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/threading/sequenced_worker_pool.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/policy/proto/cloud/device_management_local.pb.h" #include "chromeos/dbus/mock_cryptohome_client.h" #include "chromeos/dbus/mock_session_manager_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "policy/policy_constants.h" #include "policy/proto/cloud_policy.pb.h" #include "testing/gmock/include/gmock/gmock.h" diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc index bc6372c..455cdaf 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.cc @@ -6,8 +6,8 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" #include "chrome/browser/signin/profile_oauth2_token_service.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" #include "content/public/browser/notification_source.h" #include "google_apis/gaia/gaia_constants.h" diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h index 8c57185..286dd51 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h +++ b/chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h @@ -6,8 +6,8 @@ #define CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_TOKEN_FORWARDER_H_ #include "base/basictypes.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" #include "components/browser_context_keyed_service/browser_context_keyed_service.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" #include "google_apis/gaia/oauth2_token_service.h" class ProfileOAuth2TokenService; diff --git a/chrome/browser/chromeos/policy/user_network_configuration_updater_factory.cc b/chrome/browser/chromeos/policy/user_network_configuration_updater_factory.cc index e22e119..b7f8037 100644 --- a/chrome/browser/chromeos/policy/user_network_configuration_updater_factory.cc +++ b/chrome/browser/chromeos/policy/user_network_configuration_updater_factory.cc @@ -11,7 +11,6 @@ #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" @@ -20,6 +19,7 @@ #include "chromeos/network/network_handler.h" #include "chromeos/network/onc/onc_certificate_importer_impl.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace policy { diff --git a/chrome/browser/chromeos/policy/user_policy_disk_cache.cc b/chrome/browser/chromeos/policy/user_policy_disk_cache.cc index e6a669b..bf48419 100644 --- a/chrome/browser/chromeos/policy/user_policy_disk_cache.cc +++ b/chrome/browser/chromeos/policy/user_policy_disk_cache.cc @@ -10,8 +10,8 @@ #include "base/message_loop/message_loop_proxy.h" #include "base/metrics/histogram.h" #include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/enterprise_metrics.h" #include "chrome/browser/policy/proto/cloud/device_management_local.pb.h" +#include "components/policy/core/common/cloud/enterprise_metrics.h" #include "content/public/browser/browser_thread.h" namespace em = enterprise_management; diff --git a/chrome/browser/chromeos/policy/user_policy_token_loader.cc b/chrome/browser/chromeos/policy/user_policy_token_loader.cc index 0df0966..5a47c84 100644 --- a/chrome/browser/chromeos/policy/user_policy_token_loader.cc +++ b/chrome/browser/chromeos/policy/user_policy_token_loader.cc @@ -10,8 +10,8 @@ #include "base/message_loop/message_loop_proxy.h" #include "base/metrics/histogram.h" #include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/enterprise_metrics.h" #include "chrome/browser/policy/proto/cloud/device_management_local.pb.h" +#include "components/policy/core/common/cloud/enterprise_metrics.h" namespace policy { diff --git a/chrome/browser/chromeos/proxy_config_service_impl.cc b/chrome/browser/chromeos/proxy_config_service_impl.cc index 335a309..fe58bc1f 100644 --- a/chrome/browser/chromeos/proxy_config_service_impl.cc +++ b/chrome/browser/chromeos/proxy_config_service_impl.cc @@ -15,7 +15,6 @@ #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/net/proxy_config_handler.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/prefs/proxy_config_dictionary.h" #include "chrome/browser/prefs/proxy_prefs.h" #include "chrome/common/pref_names.h" @@ -25,6 +24,7 @@ #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/onc/onc_utils.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace chromeos { diff --git a/chrome/browser/chromeos/settings/cros_settings_unittest.cc b/chrome/browser/chromeos/settings/cros_settings_unittest.cc index a708c7f..a245993 100644 --- a/chrome/browser/chromeos/settings/cros_settings_unittest.cc +++ b/chrome/browser/chromeos/settings/cros_settings_unittest.cc @@ -14,12 +14,12 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "content/public/test/test_browser_thread.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chrome/browser/chromeos/settings/device_settings_provider.cc b/chrome/browser/chromeos/settings/device_settings_provider.cc index 439c271b..fa51598 100644 --- a/chrome/browser/chromeos/settings/device_settings_provider.cc +++ b/chrome/browser/chromeos/settings/device_settings_provider.cc @@ -20,7 +20,6 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/device_settings_cache.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/browser/ui/options/options_util.h" #include "chrome/installer/util/google_update_settings.h" @@ -32,6 +31,7 @@ #include "chromeos/network/network_state_handler.h" #include "chromeos/network/shill_property_util.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "third_party/cros_system_api/dbus/service_constants.h" using google::protobuf::RepeatedField; diff --git a/chrome/browser/chromeos/settings/device_settings_service.h b/chrome/browser/chromeos/settings/device_settings_service.h index d2b516a..1d66569 100644 --- a/chrome/browser/chromeos/settings/device_settings_service.h +++ b/chrome/browser/chromeos/settings/device_settings_service.h @@ -15,9 +15,9 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/observer_list.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" #include "chromeos/cert_loader.h" #include "chromeos/dbus/session_manager_client.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" namespace crypto { class RSAPrivateKey; diff --git a/chrome/browser/chromeos/settings/session_manager_operation.cc b/chrome/browser/chromeos/settings/session_manager_operation.cc index e3718f9..bbeaed3 100644 --- a/chrome/browser/chromeos/settings/session_manager_operation.cc +++ b/chrome/browser/chromeos/settings/session_manager_operation.cc @@ -13,9 +13,9 @@ #include "base/threading/sequenced_worker_pool.h" #include "base/time/time.h" #include "chrome/browser/chromeos/settings/owner_key_util.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "content/public/browser/browser_thread.h" #include "crypto/rsa_private_key.h" #include "crypto/signature_creator.h" diff --git a/chrome/browser/chromeos/settings/session_manager_operation_unittest.cc b/chrome/browser/chromeos/settings/session_manager_operation_unittest.cc index 1023aa0..ac77d05 100644 --- a/chrome/browser/chromeos/settings/session_manager_operation_unittest.cc +++ b/chrome/browser/chromeos/settings/session_manager_operation_unittest.cc @@ -12,11 +12,11 @@ #include "base/message_loop/message_loop.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" #include "chrome/browser/chromeos/settings/mock_owner_key_util.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" -#include "chrome/browser/policy/cloud/policy_builder.h" #include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "content/public/test/test_browser_thread.h" #include "crypto/rsa_private_key.h" #include "testing/gmock/include/gmock/gmock.h" diff --git a/chrome/browser/chromeos/system/ash_system_tray_delegate.cc b/chrome/browser/chromeos/system/ash_system_tray_delegate.cc index e1f6c83..1e3fcf0 100644 --- a/chrome/browser/chromeos/system/ash_system_tray_delegate.cc +++ b/chrome/browser/chromeos/system/ash_system_tray_delegate.cc @@ -71,7 +71,6 @@ #include "chrome/browser/google/google_util.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/volume_controller_chromeos.h" #include "chrome/browser/ui/browser.h" @@ -92,6 +91,7 @@ #include "chromeos/ime/input_method_manager.h" #include "chromeos/ime/xkeyboard.h" #include "chromeos/login/login_state.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_service.h" diff --git a/chrome/browser/download/download_dir_policy_handler.h b/chrome/browser/download/download_dir_policy_handler.h index 3620ef6..2b26689 100644 --- a/chrome/browser/download/download_dir_policy_handler.h +++ b/chrome/browser/download/download_dir_policy_handler.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_DOWNLOAD_DOWNLOAD_DIR_POLICY_HANDLER_H_ #define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_DIR_POLICY_HANDLER_H_ -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/download/download_dir_policy_handler_unittest.cc b/chrome/browser/download/download_dir_policy_handler_unittest.cc index 503f3b4..49e6ae2 100644 --- a/chrome/browser/download/download_dir_policy_handler_unittest.cc +++ b/chrome/browser/download/download_dir_policy_handler_unittest.cc @@ -5,9 +5,9 @@ #include "base/values.h" #include "chrome/browser/download/download_dir_policy_handler.h" #include "chrome/browser/download/download_prefs.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/configuration_policy_pref_store_unittest.h" +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "components/policy/core/common/policy_map.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc index b848f4d..90f6425 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc @@ -15,7 +15,6 @@ #include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h" #include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h" #include "chrome/browser/extensions/extension_function_test_utils.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chromeos/attestation/attestation_constants.h" @@ -25,6 +24,7 @@ #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/mock_cryptohome_client.h" #include "chromeos/settings/cros_settings_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/service_constants.h" diff --git a/chrome/browser/extensions/api/storage/managed_value_store_cache.h b/chrome/browser/extensions/api/storage/managed_value_store_cache.h index 6e08b14..07c802f 100644 --- a/chrome/browser/extensions/api/storage/managed_value_store_cache.h +++ b/chrome/browser/extensions/api/storage/managed_value_store_cache.h @@ -16,7 +16,7 @@ #include "base/memory/scoped_ptr.h" #include "chrome/browser/extensions/api/storage/settings_observer.h" #include "chrome/browser/extensions/api/storage/value_store_cache.h" -#include "chrome/browser/policy/policy_service.h" +#include "components/policy/core/common/policy_service.h" class Profile; diff --git a/chrome/browser/extensions/policy_handlers.h b/chrome/browser/extensions/policy_handlers.h index 4446238..7460d67 100644 --- a/chrome/browser/extensions/policy_handlers.h +++ b/chrome/browser/extensions/policy_handlers.h @@ -7,7 +7,7 @@ #include "base/memory/scoped_ptr.h" #include "base/values.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { class PolicyMap; diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index 51a742d..770fa84 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc @@ -41,10 +41,10 @@ #include "chrome/browser/net/proxy_service_factory.h" #include "chrome/browser/net/sdch_dictionary_fetcher.h" #include "chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" +#include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "net/base/host_mapping_rules.h" #include "net/base/net_util.h" diff --git a/chrome/browser/net/disk_cache_dir_policy_handler.h b/chrome/browser/net/disk_cache_dir_policy_handler.h index 6188f6c..d553aac 100644 --- a/chrome/browser/net/disk_cache_dir_policy_handler.h +++ b/chrome/browser/net/disk_cache_dir_policy_handler.h @@ -7,7 +7,7 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { diff --git a/chrome/browser/net/proxy_policy_handler.cc b/chrome/browser/net/proxy_policy_handler.cc index 9e848b7..f1123df 100644 --- a/chrome/browser/net/proxy_policy_handler.cc +++ b/chrome/browser/net/proxy_policy_handler.cc @@ -8,10 +8,10 @@ #include "base/prefs/pref_value_map.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" -#include "chrome/browser/policy/configuration_policy_handler.h" #include "chrome/browser/prefs/proxy_config_dictionary.h" #include "chrome/browser/prefs/proxy_prefs.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_handler.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" #include "grit/component_strings.h" diff --git a/chrome/browser/net/proxy_policy_handler.h b/chrome/browser/net/proxy_policy_handler.h index b4208d4..2af0a65 100644 --- a/chrome/browser/net/proxy_policy_handler.h +++ b/chrome/browser/net/proxy_policy_handler.h @@ -8,7 +8,7 @@ #include <string> #include "base/basictypes.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { diff --git a/chrome/browser/net/proxy_policy_handler_unittest.cc b/chrome/browser/net/proxy_policy_handler_unittest.cc index bbaa879..023eb26 100644 --- a/chrome/browser/net/proxy_policy_handler_unittest.cc +++ b/chrome/browser/net/proxy_policy_handler_unittest.cc @@ -8,13 +8,13 @@ #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/net/proxy_policy_handler.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/configuration_policy_pref_store_unittest.h" -#include "chrome/browser/policy/policy_service_impl.h" +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" #include "chrome/browser/policy/policy_transformations.h" #include "chrome/browser/prefs/proxy_config_dictionary.h" #include "chrome/browser/prefs/proxy_prefs.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" +#include "components/policy/core/common/policy_service_impl.h" #include "policy/policy_constants.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chrome/browser/policy/DEPS b/chrome/browser/policy/DEPS index 36c505a..c32324a 100644 --- a/chrome/browser/policy/DEPS +++ b/chrome/browser/policy/DEPS @@ -1,56 +1,8 @@ -# The //chrome/browser/policy code is being converted into a component at -# //components/policy. This DEPS file is temporarily restricting the include -# rules for this code; once all the exceptions are fixed then the code will -# be moved, and this file will be removed. -# http://crbug.com/271392 - include_rules = [ - "-chrome", - "-chromeos", - "-content", - "+chrome/browser/policy", - "+components/json_schema", + "+chrome", + "+chromeos", + "+content/public/browser", + "+content/public/common", + "+content/public/test", + "+content/test/net", ] - -specific_include_rules = { - # These files will stay. - r"(browser_policy_connector|" - r"configuration_policy_handler_android|" - r"configuration_policy_handler_list_factory|" - r"file_selection_dialogs_policy_handler|" - r"file_selection_dialogs_policy_handler_unittest|" - r"generate_policy_source_unittest|" - r"javascript_policy_handler|" - r"javascript_policy_handler_unittest|" - r"managed_mode_policy_provider|" - r"policy_browsertest|" - r"policy_path_parser|" - r"policy_path_parser_linux|" - r"policy_path_parser_mac|" - r"policy_path_parser_unittest|" - r"policy_path_parser_win|" - r"policy_prefs_browsertest|" - r"policy_transformations|" - r"policy_transformations_unittest|" - r"profile_policy_connector|" - r"profile_policy_connector_factory|" - r"url_blacklist_manager|" - r"url_blacklist_manager_unittest|" - r"url_blacklist_policy_handler|" - r"url_blacklist_policy_handler_unittest)" - r"\.(cc|h)": [ - "+chrome", - "+chromeos", - "+content/public/browser", - "+content/public/common", - "+content/public/test", - "+content/test/net", - ], - - # These will go in the component but can use the public content API. - r"(schema_registry_service_factory)" - r"\.(cc|h)": [ - "+content/public/browser", - "+content/public/common", - ], -} diff --git a/chrome/browser/policy/autofill_policy_handler.h b/chrome/browser/policy/autofill_policy_handler.h index a43908a..4668efb8 100644 --- a/chrome/browser/policy/autofill_policy_handler.h +++ b/chrome/browser/policy/autofill_policy_handler.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_POLICY_AUTOFILL_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_AUTOFILL_POLICY_HANDLER_H_ -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/policy/browser_policy_connector.cc b/chrome/browser/policy/browser_policy_connector.cc index 04c46cc..a3bdf8b 100644 --- a/chrome/browser/policy/browser_policy_connector.cc +++ b/chrome/browser/policy/browser_policy_connector.cc @@ -25,22 +25,22 @@ #include "base/sys_info.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" -#include "chrome/browser/policy/cloud/device_management_service.h" #include "chrome/browser/policy/configuration_policy_handler_list_factory.h" -#include "chrome/browser/policy/policy_service_impl.h" -#include "chrome/browser/policy/policy_statistics_collector.h" #include "chrome/browser/policy/policy_transformations.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "components/policy/core/common/async_policy_provider.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" +#include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/configuration_policy_provider.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_pref_names.h" +#include "components/policy/core/common/policy_service_impl.h" +#include "components/policy/core/common/policy_statistics_collector.h" #include "components/policy/core/common/schema.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_client.h" @@ -53,13 +53,13 @@ #include "url/gurl.h" #if defined(OS_WIN) -#include "chrome/browser/policy/policy_loader_win.h" +#include "components/policy/core/common/policy_loader_win.h" #elif defined(OS_MACOSX) && !defined(OS_IOS) #include <CoreFoundation/CoreFoundation.h> -#include "chrome/browser/policy/policy_loader_mac.h" +#include "components/policy/core/common/policy_loader_mac.h" #include "components/policy/core/common/preferences_mac.h" #elif defined(OS_POSIX) && !defined(OS_ANDROID) -#include "chrome/browser/policy/config_dir_policy_loader.h" +#include "components/policy/core/common/config_dir_policy_loader.h" #endif #if defined(OS_CHROMEOS) diff --git a/chrome/browser/policy/browser_policy_connector.h b/chrome/browser/policy/browser_policy_connector.h index 268b337..49a6899 100644 --- a/chrome/browser/policy/browser_policy_connector.h +++ b/chrome/browser/policy/browser_policy_connector.h @@ -11,8 +11,8 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/configuration_policy_handler_list.h" +#include "components/policy/core/browser/configuration_policy_handler_list.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/schema.h" #include "components/policy/core/common/schema_registry.h" diff --git a/chrome/browser/policy/cloud/DEPS b/chrome/browser/policy/cloud/DEPS index 788d27a..30af644 100644 --- a/chrome/browser/policy/cloud/DEPS +++ b/chrome/browser/policy/cloud/DEPS @@ -19,6 +19,9 @@ specific_include_rules = { r"component_cloud_policy_browsertest|" r"device_management_service_browsertest|" r"test_request_interceptor|" + r"user_cloud_policy_invalidator|" + r"user_cloud_policy_invalidator_factory|" + r"user_cloud_policy_manager_factory|" r"user_policy_signin_service_android|" r"user_policy_signin_service_base|" r"user_policy_signin_service|" @@ -49,30 +52,4 @@ specific_include_rules = { r"cloud_policy_invalidator_unittest\.cc": [ "+chrome/browser/invalidation/fake_invalidation_service.h", ], - - r"cloud_policy_manager_unittest\.cc": [ - "+chrome/browser/invalidation/fake_invalidation_service.h", - ], - - r"user_cloud_policy_invalidator\.cc": [ - "+chrome/browser/chrome_notification_types.h", - "+chrome/browser/invalidation/invalidation_service_factory.h", - "+content/public/browser/notification_source.h", - ], - - r"user_cloud_policy_invalidator_factory\.cc": [ - "+chrome/browser/invalidation/invalidation_service_factory.h", - "+chrome/browser/profiles/profile.h", - "+chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h", - "+chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h", - ], - - r"user_cloud_policy_invalidator\.h": [ - "+content/public/browser/notification_observer.h", - "+content/public/browser/notification_registrar.h", - ], - - r"user_cloud_policy_manager_factory\.cc": [ - "+content/public/browser/browser_context.h", - ], } diff --git a/chrome/browser/policy/cloud/cloud_external_data_manager.cc b/chrome/browser/policy/cloud/cloud_external_data_manager.cc deleted file mode 100644 index 797ffd0..0000000 --- a/chrome/browser/policy/cloud/cloud_external_data_manager.cc +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" - -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "net/url_request/url_request_context_getter.h" - -namespace policy { - -CloudExternalDataManager::MetadataEntry::MetadataEntry() { -} - -CloudExternalDataManager::MetadataEntry::MetadataEntry(const std::string& url, - const std::string& hash) - : url(url), - hash(hash) { -} - -bool CloudExternalDataManager::MetadataEntry::operator!=( - const MetadataEntry& other) const { - return url != other.url || hash != other.hash; -} - -CloudExternalDataManager::CloudExternalDataManager() : policy_store_(NULL), - weak_factory_(this) { -} - -CloudExternalDataManager::~CloudExternalDataManager() { -} - -void CloudExternalDataManager::SetPolicyStore(CloudPolicyStore* policy_store) { - weak_factory_.InvalidateWeakPtrs(); - policy_store_ = policy_store; - if (policy_store_) - policy_store_->SetExternalDataManager(weak_factory_.GetWeakPtr()); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_external_data_manager.h b/chrome/browser/policy/cloud/cloud_external_data_manager.h deleted file mode 100644 index 112312d..0000000 --- a/chrome/browser/policy/cloud/cloud_external_data_manager.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_EXTERNAL_DATA_MANAGER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_EXTERNAL_DATA_MANAGER_H_ - -#include <map> -#include <string> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "components/policy/core/common/external_data_manager.h" - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -class CloudPolicyStore; - -// Downloads, verifies, caches and retrieves external data referenced by -// policies. -// This a common base class used by cloud policy implementations and mocks. -class CloudExternalDataManager : public ExternalDataManager { - public: - struct MetadataEntry { - MetadataEntry(); - MetadataEntry(const std::string& url, const std::string& hash); - - bool operator!=(const MetadataEntry& other) const; - - std::string url; - std::string hash; - }; - // Maps from policy names to the metadata specifying the external data that - // each of the policies references. - typedef std::map<std::string, MetadataEntry> Metadata; - - CloudExternalDataManager(); - virtual ~CloudExternalDataManager(); - - // Sets the source of external data references to |policy_store|. The manager - // will start observing |policy_store| so that when external data references - // change, obsolete data can be deleted and new data can be downloaded. If the - // |policy_store| is destroyed before the manager, the connection must be - // severed first by calling SetPolicyStore(NULL). - virtual void SetPolicyStore(CloudPolicyStore* policy_store); - - // Called by the |policy_store_| when policy changes. - virtual void OnPolicyStoreLoaded() = 0; - - // Allows the manager to download external data by constructing URLFetchers - // from |request_context|. - virtual void Connect( - scoped_refptr<net::URLRequestContextGetter> request_context) = 0; - - // Prevents further external data downloads and aborts any downloads currently - // in progress. - virtual void Disconnect() = 0; - - protected: - CloudPolicyStore* policy_store_; // Not owned. - - base::WeakPtrFactory<CloudExternalDataManager> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(CloudExternalDataManager); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_EXTERNAL_DATA_MANAGER_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc index cdf8915..f487ccf 100644 --- a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc @@ -17,20 +17,20 @@ #include "chrome/browser/invalidation/fake_invalidation_service.h" #include "chrome/browser/invalidation/invalidation_service_factory.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/policy/test/local_policy_test_server.h" -#include "chrome/browser/policy/test/policy_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service.h" +#include "components/policy/core/common/policy_test_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" diff --git a/chrome/browser/policy/cloud/cloud_policy_client.cc b/chrome/browser/policy/cloud/cloud_policy_client.cc deleted file mode 100644 index da09698..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_client.cc +++ /dev/null @@ -1,458 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_client.h" - -#include "base/bind.h" -#include "base/guid.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "google_apis/gaia/gaia_constants.h" -#include "google_apis/gaia/gaia_urls.h" -#include "net/url_request/url_request_context_getter.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -// Translates the DeviceRegisterResponse::DeviceMode |mode| to the enum used -// internally to represent different device modes. -DeviceMode TranslateProtobufDeviceMode( - em::DeviceRegisterResponse::DeviceMode mode) { - switch (mode) { - case em::DeviceRegisterResponse::ENTERPRISE: - return DEVICE_MODE_ENTERPRISE; - case em::DeviceRegisterResponse::RETAIL: - return DEVICE_MODE_RETAIL_KIOSK; - } - LOG(ERROR) << "Unknown enrollment mode in registration response: " << mode; - return DEVICE_MODE_NOT_SET; -} - -bool IsChromePolicy(const std::string& type) { - return type == dm_protocol::kChromeDevicePolicyType || - type == GetChromeUserPolicyType(); -} - -} // namespace - -CloudPolicyClient::Observer::~Observer() {} - -void CloudPolicyClient::Observer::OnRobotAuthCodesFetched( - CloudPolicyClient* client) {} - -CloudPolicyClient::StatusProvider::~StatusProvider() {} - -CloudPolicyClient::CloudPolicyClient( - const std::string& machine_id, - const std::string& machine_model, - UserAffiliation user_affiliation, - StatusProvider* status_provider, - DeviceManagementService* service, - scoped_refptr<net::URLRequestContextGetter> request_context) - : machine_id_(machine_id), - machine_model_(machine_model), - user_affiliation_(user_affiliation), - device_mode_(DEVICE_MODE_NOT_SET), - submit_machine_id_(false), - public_key_version_(-1), - public_key_version_valid_(false), - invalidation_version_(0), - fetched_invalidation_version_(0), - service_(service), // Can be NULL for unit tests. - status_provider_(status_provider), // Can be NULL for unit tests. - status_(DM_STATUS_SUCCESS), - request_context_(request_context) { -} - -CloudPolicyClient::~CloudPolicyClient() { - STLDeleteValues(&responses_); -} - -void CloudPolicyClient::SetupRegistration(const std::string& dm_token, - const std::string& client_id) { - DCHECK(!dm_token.empty()); - DCHECK(!client_id.empty()); - DCHECK(!is_registered()); - - dm_token_ = dm_token; - client_id_ = client_id; - request_job_.reset(); - STLDeleteValues(&responses_); - - NotifyRegistrationStateChanged(); -} - -void CloudPolicyClient::Register(em::DeviceRegisterRequest::Type type, - const std::string& auth_token, - const std::string& client_id, - bool is_auto_enrollement, - const std::string& requisition) { - DCHECK(service_); - DCHECK(!auth_token.empty()); - DCHECK(!is_registered()); - - if (client_id.empty()) { - // Generate a new client ID. This is intentionally done on each new - // registration request in order to preserve privacy. Reusing IDs would mean - // the server could track clients by their registration attempts. - client_id_ = base::GenerateGUID(); - } else { - client_id_ = client_id; - } - - request_job_.reset( - service_->CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, - GetRequestContext())); - request_job_->SetOAuthToken(auth_token); - request_job_->SetClientID(client_id_); - - em::DeviceRegisterRequest* request = - request_job_->GetRequest()->mutable_register_request(); - if (!client_id.empty()) - request->set_reregister(true); - request->set_type(type); - if (!machine_id_.empty()) - request->set_machine_id(machine_id_); - if (!machine_model_.empty()) - request->set_machine_model(machine_model_); - if (is_auto_enrollement) - request->set_auto_enrolled(true); - if (!requisition.empty()) - request->set_requisition(requisition); - - request_job_->SetRetryCallback( - base::Bind(&CloudPolicyClient::OnRetryRegister, base::Unretained(this))); - - request_job_->Start(base::Bind(&CloudPolicyClient::OnRegisterCompleted, - base::Unretained(this))); -} - -void CloudPolicyClient::SetInvalidationInfo( - int64 version, - const std::string& payload) { - invalidation_version_ = version; - invalidation_payload_ = payload; -} - -void CloudPolicyClient::FetchPolicy() { - CHECK(is_registered()); - CHECK(!namespaces_to_fetch_.empty()); - - request_job_.reset( - service_->CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, - GetRequestContext())); - request_job_->SetDMToken(dm_token_); - request_job_->SetClientID(client_id_); - request_job_->SetUserAffiliation(user_affiliation_); - - em::DeviceManagementRequest* request = request_job_->GetRequest(); - - // Build policy fetch requests. - em::DevicePolicyRequest* policy_request = request->mutable_policy_request(); - for (NamespaceSet::iterator it = namespaces_to_fetch_.begin(); - it != namespaces_to_fetch_.end(); ++it) { - em::PolicyFetchRequest* fetch_request = policy_request->add_request(); - fetch_request->set_policy_type(it->first); - if (!it->second.empty()) - fetch_request->set_settings_entity_id(it->second); - -#if defined(OS_CHROMEOS) - // All policy types on ChromeOS ask for a signed policy blob. - fetch_request->set_signature_type(em::PolicyFetchRequest::SHA1_RSA); -#else - // Don't request signed blobs for desktop policy. - fetch_request->set_signature_type(em::PolicyFetchRequest::NONE); -#endif - if (public_key_version_valid_) - fetch_request->set_public_key_version(public_key_version_); - - // These fields are included only in requests for chrome policy. - if (IsChromePolicy(it->first)) { - if (submit_machine_id_ && !machine_id_.empty()) - fetch_request->set_machine_id(machine_id_); - if (!last_policy_timestamp_.is_null()) { - base::TimeDelta timestamp( - last_policy_timestamp_ - base::Time::UnixEpoch()); - fetch_request->set_timestamp(timestamp.InMilliseconds()); - } - if (!invalidation_payload_.empty()) { - fetch_request->set_invalidation_version(invalidation_version_); - fetch_request->set_invalidation_payload(invalidation_payload_); - } - } - } - - // Add status data. - if (status_provider_) { - if (!status_provider_->GetDeviceStatus( - request->mutable_device_status_report_request())) { - request->clear_device_status_report_request(); - } - if (!status_provider_->GetSessionStatus( - request->mutable_session_status_report_request())) { - request->clear_session_status_report_request(); - } - } - - // Set the fetched invalidation version to the latest invalidation version - // since it is now the invalidation version used for the latest fetch. - fetched_invalidation_version_ = invalidation_version_; - - // Fire the job. - request_job_->Start(base::Bind(&CloudPolicyClient::OnPolicyFetchCompleted, - base::Unretained(this))); -} - -void CloudPolicyClient::FetchRobotAuthCodes(const std::string& auth_token) { - CHECK(is_registered()); - DCHECK(!auth_token.empty()); - - request_job_.reset(service_->CreateJob( - DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH, - GetRequestContext())); - // The credentials of a domain user are needed in order to mint a new OAuth2 - // authorization token for the robot account. - request_job_->SetOAuthToken(auth_token); - request_job_->SetDMToken(dm_token_); - request_job_->SetClientID(client_id_); - - em::DeviceServiceApiAccessRequest* request = - request_job_->GetRequest()->mutable_service_api_access_request(); - request->set_oauth2_client_id( - GaiaUrls::GetInstance()->oauth2_chrome_client_id()); - request->add_auth_scope(GaiaConstants::kAnyApiOAuth2Scope); - - request_job_->Start( - base::Bind(&CloudPolicyClient::OnFetchRobotAuthCodesCompleted, - base::Unretained(this))); -} - -void CloudPolicyClient::Unregister() { - DCHECK(service_); - request_job_.reset( - service_->CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, - GetRequestContext())); - request_job_->SetDMToken(dm_token_); - request_job_->SetClientID(client_id_); - request_job_->GetRequest()->mutable_unregister_request(); - request_job_->Start(base::Bind(&CloudPolicyClient::OnUnregisterCompleted, - base::Unretained(this))); -} - -void CloudPolicyClient::UploadCertificate( - const std::string& certificate_data, - const CloudPolicyClient::StatusCallback& callback) { - CHECK(is_registered()); - request_job_.reset( - service_->CreateJob(DeviceManagementRequestJob::TYPE_UPLOAD_CERTIFICATE, - GetRequestContext())); - request_job_->SetDMToken(dm_token_); - request_job_->SetClientID(client_id_); - - em::DeviceManagementRequest* request = request_job_->GetRequest(); - request->mutable_cert_upload_request()->set_device_certificate( - certificate_data); - - DeviceManagementRequestJob::Callback job_callback = base::Bind( - &CloudPolicyClient::OnCertificateUploadCompleted, - base::Unretained(this), - callback); - request_job_->Start(job_callback); -} - -void CloudPolicyClient::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void CloudPolicyClient::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -void CloudPolicyClient::AddNamespaceToFetch(const PolicyNamespaceKey& key) { - namespaces_to_fetch_.insert(key); -} - -void CloudPolicyClient::RemoveNamespaceToFetch(const PolicyNamespaceKey& key) { - namespaces_to_fetch_.erase(key); -} - -const em::PolicyFetchResponse* CloudPolicyClient::GetPolicyFor( - const PolicyNamespaceKey& key) const { - ResponseMap::const_iterator it = responses_.find(key); - return it == responses_.end() ? NULL : it->second; -} - -scoped_refptr<net::URLRequestContextGetter> -CloudPolicyClient::GetRequestContext() { - return request_context_; -} - -void CloudPolicyClient::OnRetryRegister(DeviceManagementRequestJob* job) { - DCHECK_EQ(request_job_.get(), job); - // If the initial request managed to get to the server but the response didn't - // arrive at the client then retrying with the same client ID will fail. - // Set the re-registration flag so that the server accepts it. - // If the server hasn't seen the client ID before then it will also accept - // the re-registration. - job->GetRequest()->mutable_register_request()->set_reregister(true); -} - -void CloudPolicyClient::OnRegisterCompleted( - DeviceManagementStatus status, - int net_error, - const em::DeviceManagementResponse& response) { - if (status == DM_STATUS_SUCCESS && - (!response.has_register_response() || - !response.register_response().has_device_management_token())) { - LOG(WARNING) << "Invalid registration response."; - status = DM_STATUS_RESPONSE_DECODING_ERROR; - } - - status_ = status; - if (status == DM_STATUS_SUCCESS) { - dm_token_ = response.register_response().device_management_token(); - DVLOG(1) << "Client registration complete - DMToken = " << dm_token_; - - // Device mode is only relevant for device policy really, it's the - // responsibility of the consumer of the field to check validity. - device_mode_ = DEVICE_MODE_NOT_SET; - if (response.register_response().has_enrollment_type()) { - device_mode_ = TranslateProtobufDeviceMode( - response.register_response().enrollment_type()); - } - - NotifyRegistrationStateChanged(); - } else { - NotifyClientError(); - } -} - -void CloudPolicyClient::OnFetchRobotAuthCodesCompleted( - DeviceManagementStatus status, - int net_error, - const em::DeviceManagementResponse& response) { - if (status == DM_STATUS_SUCCESS && - (!response.has_service_api_access_response() || - response.service_api_access_response().auth_code().empty())) { - LOG(WARNING) << "Invalid service api access response."; - status = DM_STATUS_RESPONSE_DECODING_ERROR; - } - - status_ = status; - if (status == DM_STATUS_SUCCESS) { - robot_api_auth_code_ = response.service_api_access_response().auth_code(); - DVLOG(1) << "Device robot account auth code fetch complete - code = " - << robot_api_auth_code_; - - NotifyRobotAuthCodesFetched(); - } else { - NotifyClientError(); - } -} - -void CloudPolicyClient::OnPolicyFetchCompleted( - DeviceManagementStatus status, - int net_error, - const em::DeviceManagementResponse& response) { - if (status == DM_STATUS_SUCCESS) { - if (!response.has_policy_response() || - response.policy_response().response_size() == 0) { - LOG(WARNING) << "Empty policy response."; - status = DM_STATUS_RESPONSE_DECODING_ERROR; - } - } - - status_ = status; - if (status == DM_STATUS_SUCCESS) { - const em::DevicePolicyResponse& policy_response = - response.policy_response(); - STLDeleteValues(&responses_); - for (int i = 0; i < policy_response.response_size(); ++i) { - const em::PolicyFetchResponse& response = policy_response.response(i); - em::PolicyData policy_data; - if (!policy_data.ParseFromString(response.policy_data()) || - !policy_data.IsInitialized() || - !policy_data.has_policy_type()) { - LOG(WARNING) << "Invalid PolicyData received, ignoring"; - continue; - } - const std::string& type = policy_data.policy_type(); - std::string entity_id; - if (policy_data.has_settings_entity_id()) - entity_id = policy_data.settings_entity_id(); - PolicyNamespaceKey key(type, entity_id); - if (ContainsKey(responses_, key)) { - LOG(WARNING) << "Duplicate PolicyFetchResponse for type: " - << type << ", entity: " << entity_id << ", ignoring"; - continue; - } - responses_[key] = new em::PolicyFetchResponse(response); - } - if (status_provider_) - status_provider_->OnSubmittedSuccessfully(); - NotifyPolicyFetched(); - } else { - NotifyClientError(); - } -} - -void CloudPolicyClient::OnUnregisterCompleted( - DeviceManagementStatus status, - int net_error, - const em::DeviceManagementResponse& response) { - if (status == DM_STATUS_SUCCESS && !response.has_unregister_response()) { - // Assume unregistration has succeeded either way. - LOG(WARNING) << "Empty unregistration response."; - } - - status_ = status; - if (status == DM_STATUS_SUCCESS) { - dm_token_.clear(); - NotifyRegistrationStateChanged(); - } else { - NotifyClientError(); - } -} - -void CloudPolicyClient::OnCertificateUploadCompleted( - const CloudPolicyClient::StatusCallback& callback, - DeviceManagementStatus status, - int net_error, - const enterprise_management::DeviceManagementResponse& response) { - if (status == DM_STATUS_SUCCESS && !response.has_cert_upload_response()) { - LOG(WARNING) << "Empty upload certificate response."; - callback.Run(false); - return; - } - - status_ = status; - if (status != DM_STATUS_SUCCESS) { - NotifyClientError(); - callback.Run(false); - return; - } - callback.Run(true); -} - -void CloudPolicyClient::NotifyPolicyFetched() { - FOR_EACH_OBSERVER(Observer, observers_, OnPolicyFetched(this)); -} - -void CloudPolicyClient::NotifyRegistrationStateChanged() { - FOR_EACH_OBSERVER(Observer, observers_, OnRegistrationStateChanged(this)); -} - -void CloudPolicyClient::NotifyRobotAuthCodesFetched() { - FOR_EACH_OBSERVER(Observer, observers_, OnRobotAuthCodesFetched(this)); -} - -void CloudPolicyClient::NotifyClientError() { - FOR_EACH_OBSERVER(Observer, observers_, OnClientError(this)); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_client.h b/chrome/browser/policy/cloud/cloud_policy_client.h deleted file mode 100644 index cd2911f..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_client.h +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_H_ - -#include <map> -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/time/time.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -class DeviceManagementRequestJob; -class DeviceManagementService; - -// Implements the core logic required to talk to the device management service. -// Also keeps track of the current state of the association with the service, -// such as whether there is a valid registration (DMToken is present in that -// case) and whether and what errors occurred in the latest request. -// -// Note that CloudPolicyClient doesn't do any validation of policy responses -// such as signature and time stamp checks. These happen once the policy gets -// installed in the cloud policy cache. -class CloudPolicyClient { - public: - // Maps a PolicyNamespaceKey to its corresponding PolicyFetchResponse. - typedef std::map<PolicyNamespaceKey, - enterprise_management::PolicyFetchResponse*> ResponseMap; - - // A callback which receives boolean status of an operation. If the operation - // succeeded, |status| is true. - typedef base::Callback<void(bool status)> StatusCallback; - - // Observer interface for state and policy changes. - class Observer { - public: - virtual ~Observer(); - - // Called when a policy fetch completes successfully. If a policy fetch - // triggers an error, OnClientError() will fire. - virtual void OnPolicyFetched(CloudPolicyClient* client) = 0; - - // Called upon registration state changes. This callback is invoked for - // successful completion of registration and unregistration requests. - virtual void OnRegistrationStateChanged(CloudPolicyClient* client) = 0; - - // Called when a request for device robot OAuth2 authorization tokens - // returns successfully. Only occurs during enrollment. Optional - // (default implementation is a noop). - virtual void OnRobotAuthCodesFetched(CloudPolicyClient* client); - - // Indicates there's been an error in a previously-issued request. - virtual void OnClientError(CloudPolicyClient* client) = 0; - }; - - // Delegate interface for supplying status information to upload to the server - // as part of the policy fetch request. - class StatusProvider { - public: - virtual ~StatusProvider(); - - // Retrieves status information to send with the next policy fetch. - // Implementations must return true if status information was filled in. - virtual bool GetDeviceStatus( - enterprise_management::DeviceStatusReportRequest* status) = 0; - virtual bool GetSessionStatus( - enterprise_management::SessionStatusReportRequest* status) = 0; - - // Called after the status information has successfully been submitted to - // the server. - virtual void OnSubmittedSuccessfully() = 0; - }; - - // |provider| and |service| are weak pointers and it's the caller's - // responsibility to keep them valid for the lifetime of CloudPolicyClient. - CloudPolicyClient( - const std::string& machine_id, - const std::string& machine_model, - UserAffiliation user_affiliation, - StatusProvider* provider, - DeviceManagementService* service, - scoped_refptr<net::URLRequestContextGetter> request_context); - virtual ~CloudPolicyClient(); - - // Sets the DMToken, thereby establishing a registration with the server. A - // policy fetch is not automatically issued but can be requested by calling - // FetchPolicy(). - virtual void SetupRegistration(const std::string& dm_token, - const std::string& client_id); - - // Attempts to register with the device management service. Results in a - // registration change or error notification. - virtual void Register( - enterprise_management::DeviceRegisterRequest::Type registration_type, - const std::string& auth_token, - const std::string& client_id, - bool is_auto_enrollment, - const std::string& requisition); - - // Sets information about a policy invalidation. Subsequent fetch operations - // will use the given info, and callers can use fetched_invalidation_version - // to determine which version of policy was fetched. - void SetInvalidationInfo(int64 version, const std::string& payload); - - // Requests a policy fetch. The client being registered is a prerequisite to - // this operation and this call will CHECK if the client is not in registered - // state. FetchPolicy() triggers a policy fetch from the cloud. A policy - // change notification is reported to the observers and the new policy blob - // can be retrieved once the policy fetch operation completes. In case of - // multiple requests to fetch policy, new requests will cancel any pending - // requests and the latest request will eventually trigger notifications. - virtual void FetchPolicy(); - - // Requests OAuth2 auth codes for the device robot account. The client being - // registered is a prerequisite to this operation and this call will CHECK if - // the client is not in registered state. - virtual void FetchRobotAuthCodes(const std::string& auth_token); - - // Sends an unregistration request to the server. - virtual void Unregister(); - - // Upload a device certificate to the server. Like FetchPolicy, this method - // requires that the client is in a registered state. |certificate_data| must - // hold the X.509 certificate data to be sent to the server. The |callback| - // will be called when the operation completes. - virtual void UploadCertificate(const std::string& certificate_data, - const StatusCallback& callback); - - // Adds an observer to be called back upon policy and state changes. - void AddObserver(Observer* observer); - - // Removes the specified observer. - void RemoveObserver(Observer* observer); - - void set_submit_machine_id(bool submit_machine_id) { - submit_machine_id_ = submit_machine_id; - } - - void set_last_policy_timestamp(const base::Time& timestamp) { - last_policy_timestamp_ = timestamp; - } - - void set_public_key_version(int public_key_version) { - public_key_version_ = public_key_version; - public_key_version_valid_ = true; - } - - void clear_public_key_version() { - public_key_version_valid_ = false; - } - - // FetchPolicy() calls will request this policy namespace. - void AddNamespaceToFetch(const PolicyNamespaceKey& policy_ns_key); - - // FetchPolicy() calls won't request the given policy namespace anymore. - void RemoveNamespaceToFetch(const PolicyNamespaceKey& policy_ns_key); - - // Whether the client is registered with the device management service. - bool is_registered() const { return !dm_token_.empty(); } - - const std::string& dm_token() const { return dm_token_; } - const std::string& client_id() const { return client_id_; } - - // The device mode as received in the registration request. - DeviceMode device_mode() const { return device_mode_; } - - // The policy responses as obtained by the last request to the cloud. These - // policies haven't gone through verification, so their contents cannot be - // trusted. Use CloudPolicyStore::policy() and CloudPolicyStore::policy_map() - // instead for making policy decisions. - const ResponseMap& responses() const { - return responses_; - } - - // Returns the policy response for |policy_ns_key|, if found in |responses()|; - // otherwise returns NULL. - const enterprise_management::PolicyFetchResponse* GetPolicyFor( - const PolicyNamespaceKey& policy_ns_key) const; - - DeviceManagementStatus status() const { - return status_; - } - - const std::string& robot_api_auth_code() const { - return robot_api_auth_code_; - } - - // Returns the invalidation version that was used for the last FetchPolicy. - // Observers can call this method from their OnPolicyFetched method to - // determine which at which invalidation version the policy was fetched. - int64 fetched_invalidation_version() const { - return fetched_invalidation_version_; - } - - scoped_refptr<net::URLRequestContextGetter> GetRequestContext(); - - protected: - // A set of PolicyNamespaceKeys to fetch. - typedef std::set<PolicyNamespaceKey> NamespaceSet; - - // Callback for retries of registration requests. - void OnRetryRegister(DeviceManagementRequestJob* job); - - // Callback for registration requests. - void OnRegisterCompleted( - DeviceManagementStatus status, - int net_error, - const enterprise_management::DeviceManagementResponse& response); - - // Callback for policy fetch requests. - void OnPolicyFetchCompleted( - DeviceManagementStatus status, - int net_error, - const enterprise_management::DeviceManagementResponse& response); - - // Callback for robot account api authorization requests. - void OnFetchRobotAuthCodesCompleted( - DeviceManagementStatus status, - int net_error, - const enterprise_management::DeviceManagementResponse& response); - - // Callback for unregistration requests. - void OnUnregisterCompleted( - DeviceManagementStatus status, - int net_error, - const enterprise_management::DeviceManagementResponse& response); - - // Callback for certificate upload requests. - void OnCertificateUploadCompleted( - const StatusCallback& callback, - DeviceManagementStatus status, - int net_error, - const enterprise_management::DeviceManagementResponse& response); - - // Observer notification helpers. - void NotifyPolicyFetched(); - void NotifyRegistrationStateChanged(); - void NotifyRobotAuthCodesFetched(); - void NotifyClientError(); - - // Data necessary for constructing policy requests. - const std::string machine_id_; - const std::string machine_model_; - const UserAffiliation user_affiliation_; - NamespaceSet namespaces_to_fetch_; - - std::string dm_token_; - DeviceMode device_mode_; - std::string client_id_; - bool submit_machine_id_; - base::Time last_policy_timestamp_; - int public_key_version_; - bool public_key_version_valid_; - std::string robot_api_auth_code_; - - // Information for the latest policy invalidation received. - int64 invalidation_version_; - std::string invalidation_payload_; - - // The invalidation version used for the most recent fetch operation. - int64 fetched_invalidation_version_; - - // Used for issuing requests to the cloud. - DeviceManagementService* service_; - scoped_ptr<DeviceManagementRequestJob> request_job_; - - // Status upload data is produced by |status_provider_|. - StatusProvider* status_provider_; - - // The policy responses returned by the last policy fetch operation. - ResponseMap responses_; - DeviceManagementStatus status_; - - ObserverList<Observer, true> observers_; - scoped_refptr<net::URLRequestContextGetter> request_context_; - - private: - DISALLOW_COPY_AND_ASSIGN(CloudPolicyClient); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_client_registration_helper.cc b/chrome/browser/policy/cloud/cloud_policy_client_registration_helper.cc deleted file mode 100644 index 8fdc3b8..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_client_registration_helper.cc +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h" - -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "base/values.h" -#include "google_apis/gaia/gaia_constants.h" -#include "google_apis/gaia/gaia_urls.h" -#include "google_apis/gaia/google_service_auth_error.h" -#include "google_apis/gaia/oauth2_token_service.h" -#include "net/url_request/url_request_context_getter.h" - -#if !defined(OS_ANDROID) -#include "google_apis/gaia/oauth2_access_token_consumer.h" -#include "google_apis/gaia/oauth2_access_token_fetcher.h" -#endif - -namespace policy { - -// OAuth2 scope for the userinfo service. -const char kServiceScopeGetUserInfo[] = - "https://www.googleapis.com/auth/userinfo.email"; - -// The key under which the hosted-domain value is stored in the UserInfo -// response. -const char kGetHostedDomainKey[] = "hd"; - -typedef base::Callback<void(const std::string&)> StringCallback; - -// This class fetches an OAuth2 token scoped for the userinfo and DM services. -// On Android, we use a special API to allow us to fetch a token for an account -// that is not yet logged in to allow fetching the token before the sign-in -// process is finished. -class CloudPolicyClientRegistrationHelper::TokenServiceHelper - : public OAuth2TokenService::Consumer { - public: - TokenServiceHelper(); - - void FetchAccessToken( - OAuth2TokenService* token_service, - const std::string& username, - const StringCallback& callback); - - private: - // OAuth2TokenService::Consumer implementation: - virtual void OnGetTokenSuccess(const OAuth2TokenService::Request* request, - const std::string& access_token, - const base::Time& expiration_time) OVERRIDE; - virtual void OnGetTokenFailure(const OAuth2TokenService::Request* request, - const GoogleServiceAuthError& error) OVERRIDE; - - StringCallback callback_; - scoped_ptr<OAuth2TokenService::Request> token_request_; -}; - -CloudPolicyClientRegistrationHelper::TokenServiceHelper::TokenServiceHelper() {} - -void CloudPolicyClientRegistrationHelper::TokenServiceHelper::FetchAccessToken( - OAuth2TokenService* token_service, - const std::string& account_id, - const StringCallback& callback) { - DCHECK(!token_request_); - // Either the caller must supply a username, or the user must be signed in - // already. - DCHECK(!account_id.empty()); - DCHECK(token_service->RefreshTokenIsAvailable(account_id)); - - callback_ = callback; - - OAuth2TokenService::ScopeSet scopes; - scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth); - scopes.insert(kServiceScopeGetUserInfo); - token_request_ = token_service->StartRequest(account_id, scopes, this); -} - -void CloudPolicyClientRegistrationHelper::TokenServiceHelper::OnGetTokenSuccess( - const OAuth2TokenService::Request* request, - const std::string& access_token, - const base::Time& expiration_time) { - DCHECK_EQ(token_request_.get(), request); - callback_.Run(access_token); -} - -void CloudPolicyClientRegistrationHelper::TokenServiceHelper::OnGetTokenFailure( - const OAuth2TokenService::Request* request, - const GoogleServiceAuthError& error) { - DCHECK_EQ(token_request_.get(), request); - callback_.Run(""); -} - -#if !defined(OS_ANDROID) -// This class fetches the OAuth2 token scoped for the userinfo and DM services. -// It uses an OAuth2AccessTokenFetcher to fetch it, given a login refresh token -// that can be used to authorize that request. This class is not needed on -// Android because we can use OAuth2TokenService to fetch tokens for accounts -// even before they are signed in. -class CloudPolicyClientRegistrationHelper::LoginTokenHelper - : public OAuth2AccessTokenConsumer { - public: - LoginTokenHelper(); - - void FetchAccessToken(const std::string& login_refresh_token, - net::URLRequestContextGetter* context, - const StringCallback& callback); - - private: - // OAuth2AccessTokenConsumer implementation: - virtual void OnGetTokenSuccess(const std::string& access_token, - const base::Time& expiration_time) OVERRIDE; - virtual void OnGetTokenFailure( - const GoogleServiceAuthError& error) OVERRIDE; - - StringCallback callback_; - scoped_ptr<OAuth2AccessTokenFetcher> oauth2_access_token_fetcher_; -}; - -CloudPolicyClientRegistrationHelper::LoginTokenHelper::LoginTokenHelper() {} - -void CloudPolicyClientRegistrationHelper::LoginTokenHelper::FetchAccessToken( - const std::string& login_refresh_token, - net::URLRequestContextGetter* context, - const StringCallback& callback) { - DCHECK(!oauth2_access_token_fetcher_); - callback_ = callback; - - // Start fetching an OAuth2 access token for the device management and - // userinfo services. - oauth2_access_token_fetcher_.reset( - new OAuth2AccessTokenFetcher(this, context)); - std::vector<std::string> scopes; - scopes.push_back(GaiaConstants::kDeviceManagementServiceOAuth); - scopes.push_back(kServiceScopeGetUserInfo); - GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); - oauth2_access_token_fetcher_->Start( - gaia_urls->oauth2_chrome_client_id(), - gaia_urls->oauth2_chrome_client_secret(), - login_refresh_token, - scopes); -} - -void CloudPolicyClientRegistrationHelper::LoginTokenHelper::OnGetTokenSuccess( - const std::string& access_token, - const base::Time& expiration_time) { - callback_.Run(access_token); -} - -void CloudPolicyClientRegistrationHelper::LoginTokenHelper::OnGetTokenFailure( - const GoogleServiceAuthError& error) { - callback_.Run(""); -} - -#endif - -CloudPolicyClientRegistrationHelper::CloudPolicyClientRegistrationHelper( - CloudPolicyClient* client, - bool should_force_load_policy, - enterprise_management::DeviceRegisterRequest::Type registration_type) - : context_(client->GetRequestContext()), - client_(client), - should_force_load_policy_(should_force_load_policy), - registration_type_(registration_type) { - DCHECK(context_); - DCHECK(client_); -} - -CloudPolicyClientRegistrationHelper::~CloudPolicyClientRegistrationHelper() { - // Clean up any pending observers in case the browser is shutdown while - // trying to register for policy. - if (client_) - client_->RemoveObserver(this); -} - - -void CloudPolicyClientRegistrationHelper::StartRegistration( - OAuth2TokenService* token_service, - const std::string& account_id, - const base::Closure& callback) { - DVLOG(1) << "Starting registration process with username"; - DCHECK(!client_->is_registered()); - callback_ = callback; - client_->AddObserver(this); - - token_service_helper_.reset(new TokenServiceHelper()); - token_service_helper_->FetchAccessToken( - token_service, - account_id, - base::Bind(&CloudPolicyClientRegistrationHelper::OnTokenFetched, - base::Unretained(this))); -} - -#if !defined(OS_ANDROID) -void CloudPolicyClientRegistrationHelper::StartRegistrationWithLoginToken( - const std::string& login_refresh_token, - const base::Closure& callback) { - DVLOG(1) << "Starting registration process with login token"; - DCHECK(!client_->is_registered()); - callback_ = callback; - client_->AddObserver(this); - - login_token_helper_.reset( - new CloudPolicyClientRegistrationHelper::LoginTokenHelper()); - login_token_helper_->FetchAccessToken( - login_refresh_token, - context_, - base::Bind(&CloudPolicyClientRegistrationHelper::OnTokenFetched, - base::Unretained(this))); -} -#endif - -void CloudPolicyClientRegistrationHelper::OnTokenFetched( - const std::string& access_token) { -#if !defined(OS_ANDROID) - login_token_helper_.reset(); -#endif - token_service_helper_.reset(); - - if (access_token.empty()) { - DLOG(WARNING) << "Could not fetch access token for " - << GaiaConstants::kDeviceManagementServiceOAuth; - RequestCompleted(); - return; - } - - // Cache the access token to be used after the GetUserInfo call. - oauth_access_token_ = access_token; - DVLOG(1) << "Fetched new scoped OAuth token:" << oauth_access_token_; - // Now we've gotten our access token - contact GAIA to see if this is a - // hosted domain. - user_info_fetcher_.reset(new UserInfoFetcher(this, context_)); - user_info_fetcher_->Start(oauth_access_token_); -} - -void CloudPolicyClientRegistrationHelper::OnGetUserInfoFailure( - const GoogleServiceAuthError& error) { - DVLOG(1) << "Failed to fetch user info from GAIA: " << error.state(); - user_info_fetcher_.reset(); - RequestCompleted(); -} - -void CloudPolicyClientRegistrationHelper::OnGetUserInfoSuccess( - const base::DictionaryValue* data) { - user_info_fetcher_.reset(); - if (!data->HasKey(kGetHostedDomainKey) && !should_force_load_policy_) { - DVLOG(1) << "User not from a hosted domain - skipping registration"; - RequestCompleted(); - return; - } - DVLOG(1) << "Registering CloudPolicyClient for user from hosted domain"; - // The user is from a hosted domain, so it's OK to register the - // CloudPolicyClient and make requests to DMServer. - if (client_->is_registered()) { - // Client should not be registered yet. - NOTREACHED(); - RequestCompleted(); - return; - } - - // Kick off registration of the CloudPolicyClient with our newly minted - // oauth_access_token_. - client_->Register(registration_type_, oauth_access_token_, - std::string(), false, std::string()); -} - -void CloudPolicyClientRegistrationHelper::OnPolicyFetched( - CloudPolicyClient* client) { - // Ignored. -} - -void CloudPolicyClientRegistrationHelper::OnRegistrationStateChanged( - CloudPolicyClient* client) { - DVLOG(1) << "Client registration succeeded"; - DCHECK_EQ(client, client_); - DCHECK(client->is_registered()); - RequestCompleted(); -} - -void CloudPolicyClientRegistrationHelper::OnClientError( - CloudPolicyClient* client) { - DVLOG(1) << "Client registration failed"; - DCHECK_EQ(client, client_); - RequestCompleted(); -} - -void CloudPolicyClientRegistrationHelper::RequestCompleted() { - if (client_) { - client_->RemoveObserver(this); - // |client_| may be freed by the callback so clear it now. - client_ = NULL; - callback_.Run(); - } -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h b/chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h deleted file mode 100644 index 8e0afe0..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_REGISTRATION_HELPER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_REGISTRATION_HELPER_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/user_info_fetcher.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" - -class OAuth2TokenService; - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -// Helper class that registers a CloudPolicyClient. It fetches an OAuth2 token -// for the DM service if needed, and checks with Gaia if the account has policy -// management enabled. -class CloudPolicyClientRegistrationHelper : public UserInfoFetcher::Delegate, - public CloudPolicyClient::Observer { - public: - // |context| and |client| are not owned and must outlive this object. - // If |should_force_load_policy| then the cloud policy registration is - // performed even if Gaia indicates that this account doesn't have management - // enabled. - CloudPolicyClientRegistrationHelper( - CloudPolicyClient* client, - bool should_force_load_policy, - enterprise_management::DeviceRegisterRequest::Type registration_type); - virtual ~CloudPolicyClientRegistrationHelper(); - - // Starts the client registration process. This version uses the - // supplied OAuth2TokenService to mint the new token for the userinfo - // and DM services, using the |account_id|. - // |callback| is invoked when the registration is complete. - void StartRegistration( - OAuth2TokenService* token_service, - const std::string& account_id, - const base::Closure& callback); - -#if !defined(OS_ANDROID) - // Starts the client registration process. The |login_refresh_token| is used - // to mint a new token for the userinfo and DM services. - // |callback| is invoked when the registration is complete. - void StartRegistrationWithLoginToken(const std::string& login_refresh_token, - const base::Closure& callback); -#endif - - private: - class TokenServiceHelper; -#if !defined(OS_ANDROID) - class LoginTokenHelper; -#endif - - void OnTokenFetched(const std::string& oauth_access_token); - - // UserInfoFetcher::Delegate implementation: - virtual void OnGetUserInfoSuccess( - const base::DictionaryValue* response) OVERRIDE; - virtual void OnGetUserInfoFailure( - const GoogleServiceAuthError& error) OVERRIDE; - - // CloudPolicyClient::Observer implementation: - virtual void OnPolicyFetched(CloudPolicyClient* client) OVERRIDE; - virtual void OnRegistrationStateChanged(CloudPolicyClient* client) OVERRIDE; - virtual void OnClientError(CloudPolicyClient* client) OVERRIDE; - - // Invoked when the registration request has been completed. - void RequestCompleted(); - - // Internal helper class that uses OAuth2TokenService to fetch an OAuth - // access token. On desktop, this is only used after the user has signed in - - // desktop platforms use LoginTokenHelper for policy fetches performed before - // signin is complete. - scoped_ptr<TokenServiceHelper> token_service_helper_; - -#if !defined(OS_ANDROID) - // Special desktop-only helper to fetch an OAuth access token prior to - // the completion of signin. Not used on Android since all token fetching - // is done via OAuth2TokenService. - scoped_ptr<LoginTokenHelper> login_token_helper_; -#endif - - // Helper class for fetching information from GAIA about the currently - // signed-in user. - scoped_ptr<UserInfoFetcher> user_info_fetcher_; - - // Access token used to register the CloudPolicyClient and also access - // GAIA to get information about the signed in user. - std::string oauth_access_token_; - - net::URLRequestContextGetter* context_; - CloudPolicyClient* client_; - bool should_force_load_policy_; - enterprise_management::DeviceRegisterRequest::Type registration_type_; - base::Closure callback_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyClientRegistrationHelper); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_REGISTRATION_HELPER_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_client_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_client_unittest.cc deleted file mode 100644 index ce2fcd92e..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_client_unittest.cc +++ /dev/null @@ -1,589 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_client.h" - -#include <map> -#include <set> - -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::Mock; -using testing::Return; -using testing::SaveArg; -using testing::StrictMock; -using testing::_; - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -const char kClientID[] = "fake-client-id"; -const char kMachineID[] = "fake-machine-id"; -const char kMachineModel[] = "fake-machine-model"; -const char kOAuthToken[] = "fake-oauth-token"; -const char kDMToken[] = "fake-dm-token"; -const char kDeviceCertificate[] = "fake-device-certificate"; -const char kRequisition[] = "fake-requisition"; - -class MockStatusProvider : public CloudPolicyClient::StatusProvider { - public: - MockStatusProvider() {} - virtual ~MockStatusProvider() {} - - MOCK_METHOD1(GetDeviceStatus, bool(em::DeviceStatusReportRequest* status)); - MOCK_METHOD1(GetSessionStatus, bool(em::SessionStatusReportRequest* status)); - MOCK_METHOD0(OnSubmittedSuccessfully, void(void)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockStatusProvider); -}; - -MATCHER_P(MatchProto, expected, "matches protobuf") { - return arg.SerializePartialAsString() == expected.SerializePartialAsString(); -} - -// A mock class to allow us to set expectations on upload certificate callbacks. -class MockUploadCertificateObserver { - public: - MockUploadCertificateObserver() {} - virtual ~MockUploadCertificateObserver() {} - - MOCK_METHOD1(OnUploadComplete, void(bool)); -}; - -} // namespace - -class CloudPolicyClientTest : public testing::Test { - protected: - CloudPolicyClientTest() - : client_id_(kClientID), - policy_ns_key_(dm_protocol::kChromeUserPolicyType, std::string()) { - em::DeviceRegisterRequest* register_request = - registration_request_.mutable_register_request(); - register_request->set_type(em::DeviceRegisterRequest::USER); - register_request->set_machine_id(kMachineID); - register_request->set_machine_model(kMachineModel); - registration_response_.mutable_register_response()-> - set_device_management_token(kDMToken); - - em::PolicyFetchRequest* policy_fetch_request = - policy_request_.mutable_policy_request()->add_request(); - policy_fetch_request->set_policy_type(dm_protocol::kChromeUserPolicyType); -#if defined(OS_CHROMEOS) - policy_fetch_request->set_signature_type(em::PolicyFetchRequest::SHA1_RSA); -#else - policy_fetch_request->set_signature_type(em::PolicyFetchRequest::NONE); -#endif - policy_response_.mutable_policy_response()->add_response()->set_policy_data( - CreatePolicyData("fake-policy-data")); - - unregistration_request_.mutable_unregister_request(); - unregistration_response_.mutable_unregister_response(); - upload_certificate_request_.mutable_cert_upload_request()-> - set_device_certificate(kDeviceCertificate); - upload_certificate_response_.mutable_cert_upload_response(); - } - - virtual void SetUp() OVERRIDE { - EXPECT_CALL(status_provider_, GetDeviceStatus(_)) - .WillRepeatedly(Return(false)); - EXPECT_CALL(status_provider_, GetSessionStatus(_)) - .WillRepeatedly(Return(false)); - CreateClient(USER_AFFILIATION_NONE); - } - - virtual void TearDown() OVERRIDE { - client_->RemoveObserver(&observer_); - } - - void Register() { - EXPECT_CALL(observer_, OnRegistrationStateChanged(_)); - client_->SetupRegistration(kDMToken, client_id_); - } - - void CreateClient(UserAffiliation user_affiliation) { - if (client_.get()) - client_->RemoveObserver(&observer_); - - request_context_ = new net::TestURLRequestContextGetter( - loop_.message_loop_proxy()); - client_.reset(new CloudPolicyClient(kMachineID, kMachineModel, - user_affiliation, &status_provider_, - &service_, - request_context_)); - client_->AddNamespaceToFetch(policy_ns_key_); - client_->AddObserver(&observer_); - } - - void ExpectRegistration(const std::string& oauth_token) { - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, - request_context_)) - .WillOnce(service_.SucceedJob(registration_response_)); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestRegister, - "", oauth_token, "", "", _, - MatchProto(registration_request_))) - .WillOnce(SaveArg<5>(&client_id_)); - } - - void ExpectPolicyFetch(const std::string& dm_token, - const std::string& user_affiliation) { - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, - request_context_)) - .WillOnce(service_.SucceedJob(policy_response_)); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestPolicy, - "", "", dm_token, user_affiliation, - client_id_, - MatchProto(policy_request_))); - } - - void ExpectUnregistration(const std::string& dm_token) { - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, - request_context_)) - .WillOnce(service_.SucceedJob(unregistration_response_)); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestUnregister, - "", "", dm_token, "", client_id_, - MatchProto(unregistration_request_))); - } - - void ExpectUploadCertificate() { - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_UPLOAD_CERTIFICATE, - request_context_)) - .WillOnce(service_.SucceedJob(upload_certificate_response_)); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestUploadCertificate, - "", "", kDMToken, "", client_id_, - MatchProto(upload_certificate_request_))); - } - - void CheckPolicyResponse() { - ASSERT_TRUE(client_->GetPolicyFor(policy_ns_key_)); - EXPECT_THAT(*client_->GetPolicyFor(policy_ns_key_), - MatchProto(policy_response_.policy_response().response(0))); - } - - std::string CreatePolicyData(const std::string& policy_value) { - em::PolicyData policy_data; - policy_data.set_policy_type(dm_protocol::kChromeUserPolicyType); - policy_data.set_policy_value(policy_value); - return policy_data.SerializeAsString(); - } - - // Request protobufs used as expectations for the client requests. - em::DeviceManagementRequest registration_request_; - em::DeviceManagementRequest policy_request_; - em::DeviceManagementRequest unregistration_request_; - em::DeviceManagementRequest upload_certificate_request_; - - // Protobufs used in successful responses. - em::DeviceManagementResponse registration_response_; - em::DeviceManagementResponse policy_response_; - em::DeviceManagementResponse unregistration_response_; - em::DeviceManagementResponse upload_certificate_response_; - - base::MessageLoop loop_; - std::string client_id_; - PolicyNamespaceKey policy_ns_key_; - MockDeviceManagementService service_; - StrictMock<MockStatusProvider> status_provider_; - StrictMock<MockCloudPolicyClientObserver> observer_; - StrictMock<MockUploadCertificateObserver> upload_certificate_observer_; - scoped_ptr<CloudPolicyClient> client_; - // Cached weak pointer to the client's request context. - net::URLRequestContextGetter* request_context_; -}; - -TEST_F(CloudPolicyClientTest, Init) { - EXPECT_CALL(service_, CreateJob(_, _)).Times(0); - EXPECT_FALSE(client_->is_registered()); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); - EXPECT_EQ(0, client_->fetched_invalidation_version()); -} - -TEST_F(CloudPolicyClientTest, SetupRegistrationAndPolicyFetch) { - EXPECT_CALL(service_, CreateJob(_, _)).Times(0); - EXPECT_CALL(observer_, OnRegistrationStateChanged(_)); - client_->SetupRegistration(kDMToken, client_id_); - EXPECT_TRUE(client_->is_registered()); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); - - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); - CheckPolicyResponse(); -} - -TEST_F(CloudPolicyClientTest, RegistrationAndPolicyFetch) { - ExpectRegistration(kOAuthToken); - EXPECT_CALL(observer_, OnRegistrationStateChanged(_)); - client_->Register(em::DeviceRegisterRequest::USER, - kOAuthToken, std::string(), false, std::string()); - EXPECT_TRUE(client_->is_registered()); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); - - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); - CheckPolicyResponse(); -} - -TEST_F(CloudPolicyClientTest, RegistrationParameters) { - registration_request_.mutable_register_request()->set_reregister(true); - registration_request_.mutable_register_request()->set_auto_enrolled(true); - registration_request_.mutable_register_request()->set_requisition( - kRequisition); - ExpectRegistration(kOAuthToken); - EXPECT_CALL(observer_, OnRegistrationStateChanged(_)); - client_->Register(em::DeviceRegisterRequest::USER, - kOAuthToken, kClientID, true, kRequisition); - EXPECT_EQ(kClientID, client_id_); -} - -TEST_F(CloudPolicyClientTest, RegistrationNoToken) { - registration_response_.mutable_register_response()-> - clear_device_management_token(); - ExpectRegistration(kOAuthToken); - EXPECT_CALL(observer_, OnClientError(_)); - client_->Register(em::DeviceRegisterRequest::USER, - kOAuthToken, std::string(), false, std::string()); - EXPECT_FALSE(client_->is_registered()); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); - EXPECT_EQ(DM_STATUS_RESPONSE_DECODING_ERROR, client_->status()); -} - -TEST_F(CloudPolicyClientTest, RegistrationFailure) { - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, - request_context_)) - .WillOnce(service_.FailJob(DM_STATUS_REQUEST_FAILED)); - EXPECT_CALL(service_, StartJob(_, _, _, _, _, _, _)); - EXPECT_CALL(observer_, OnClientError(_)); - client_->Register(em::DeviceRegisterRequest::USER, - kOAuthToken, std::string(), false, std::string()); - EXPECT_FALSE(client_->is_registered()); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); - EXPECT_EQ(DM_STATUS_REQUEST_FAILED, client_->status()); -} - -TEST_F(CloudPolicyClientTest, RetryRegistration) { - // First registration does not set the re-register flag. - EXPECT_FALSE( - registration_request_.mutable_register_request()->has_reregister()); - MockDeviceManagementJob* register_job = NULL; - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, - request_context_)) - .WillOnce(service_.CreateAsyncJob(®ister_job)); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestRegister, - "", kOAuthToken, "", "", _, - MatchProto(registration_request_))); - client_->Register(em::DeviceRegisterRequest::USER, - kOAuthToken, std::string(), false, std::string()); - EXPECT_FALSE(client_->is_registered()); - Mock::VerifyAndClearExpectations(&service_); - - // Simulate a retry callback before proceeding; the re-register flag is set. - registration_request_.mutable_register_request()->set_reregister(true); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestRegister, - "", kOAuthToken, "", "", _, - MatchProto(registration_request_))); - register_job->RetryJob(); - Mock::VerifyAndClearExpectations(&service_); - - // Subsequent retries keep the flag set. - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestRegister, - "", kOAuthToken, "", "", _, - MatchProto(registration_request_))); - register_job->RetryJob(); - Mock::VerifyAndClearExpectations(&service_); -} - -TEST_F(CloudPolicyClientTest, PolicyUpdate) { - Register(); - - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - CheckPolicyResponse(); - - policy_response_.mutable_policy_response()->clear_response(); - policy_response_.mutable_policy_response()->add_response()->set_policy_data( - CreatePolicyData("updated-fake-policy-data")); - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); - CheckPolicyResponse(); -} - -TEST_F(CloudPolicyClientTest, PolicyFetchWithMetaData) { - Register(); - - const base::Time timestamp( - base::Time::UnixEpoch() + base::TimeDelta::FromDays(20)); - client_->set_submit_machine_id(true); - client_->set_last_policy_timestamp(timestamp); - client_->set_public_key_version(42); - em::PolicyFetchRequest* policy_fetch_request = - policy_request_.mutable_policy_request()->mutable_request(0); - policy_fetch_request->set_machine_id(kMachineID); - policy_fetch_request->set_timestamp( - (timestamp - base::Time::UnixEpoch()).InMilliseconds()); - policy_fetch_request->set_public_key_version(42); - - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - CheckPolicyResponse(); -} - -TEST_F(CloudPolicyClientTest, PolicyFetchWithInvalidation) { - Register(); - - int64 previous_version = client_->fetched_invalidation_version(); - client_->SetInvalidationInfo(12345, "12345"); - EXPECT_EQ(previous_version, client_->fetched_invalidation_version()); - em::PolicyFetchRequest* policy_fetch_request = - policy_request_.mutable_policy_request()->mutable_request(0); - policy_fetch_request->set_invalidation_version(12345); - policy_fetch_request->set_invalidation_payload("12345"); - - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - CheckPolicyResponse(); - EXPECT_EQ(12345, client_->fetched_invalidation_version()); -} - -TEST_F(CloudPolicyClientTest, PolicyFetchWithInvalidationNoPayload) { - Register(); - - int64 previous_version = client_->fetched_invalidation_version(); - client_->SetInvalidationInfo(-12345, std::string()); - EXPECT_EQ(previous_version, client_->fetched_invalidation_version()); - - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - CheckPolicyResponse(); - EXPECT_EQ(-12345, client_->fetched_invalidation_version()); -} - -TEST_F(CloudPolicyClientTest, BadPolicyResponse) { - Register(); - - policy_response_.clear_policy_response(); - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnClientError(_)); - client_->FetchPolicy(); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); - EXPECT_EQ(DM_STATUS_RESPONSE_DECODING_ERROR, client_->status()); - - policy_response_.mutable_policy_response()->add_response()->set_policy_data( - CreatePolicyData("fake-policy-data")); - policy_response_.mutable_policy_response()->add_response()->set_policy_data( - CreatePolicyData("excess-fake-policy-data")); - ExpectPolicyFetch(kDMToken, dm_protocol::kValueUserAffiliationNone); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - client_->FetchPolicy(); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); - CheckPolicyResponse(); -} - -TEST_F(CloudPolicyClientTest, PolicyRequestFailure) { - Register(); - - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, - request_context_)) - .WillOnce(service_.FailJob(DM_STATUS_REQUEST_FAILED)); - EXPECT_CALL(service_, StartJob(_, _, _, _, _, _, _)); - EXPECT_CALL(observer_, OnClientError(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()).Times(0); - client_->FetchPolicy(); - EXPECT_EQ(DM_STATUS_REQUEST_FAILED, client_->status()); - EXPECT_FALSE(client_->GetPolicyFor(policy_ns_key_)); -} - -TEST_F(CloudPolicyClientTest, Unregister) { - Register(); - - ExpectUnregistration(kDMToken); - EXPECT_CALL(observer_, OnRegistrationStateChanged(_)); - client_->Unregister(); - EXPECT_FALSE(client_->is_registered()); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); -} - -TEST_F(CloudPolicyClientTest, UnregisterEmpty) { - Register(); - - unregistration_response_.clear_unregister_response(); - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, - request_context_)) - .WillOnce(service_.SucceedJob(unregistration_response_)); - EXPECT_CALL(service_, StartJob(_, _, _, _, _, _, _)); - EXPECT_CALL(observer_, OnRegistrationStateChanged(_)); - client_->Unregister(); - EXPECT_FALSE(client_->is_registered()); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); -} - -TEST_F(CloudPolicyClientTest, UnregisterFailure) { - Register(); - - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, - request_context_)) - .WillOnce(service_.FailJob(DM_STATUS_REQUEST_FAILED)); - EXPECT_CALL(service_, StartJob(_, _, _, _, _, _, _)); - EXPECT_CALL(observer_, OnClientError(_)); - client_->Unregister(); - EXPECT_TRUE(client_->is_registered()); - EXPECT_EQ(DM_STATUS_REQUEST_FAILED, client_->status()); -} - -TEST_F(CloudPolicyClientTest, PolicyFetchWithExtensionPolicy) { - Register(); - - // Setup the |expected_responses| and |policy_response_|. - static const char* kExtensions[] = { - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "cccccccccccccccccccccccccccccccc", - }; - typedef std::map<PolicyNamespaceKey, em::PolicyFetchResponse> ResponseMap; - ResponseMap expected_responses; - std::set<PolicyNamespaceKey> expected_namespaces; - PolicyNamespaceKey key(dm_protocol::kChromeUserPolicyType, std::string()); - // Copy the user policy fetch request. - expected_responses[key].CopyFrom( - policy_response_.policy_response().response(0)); - expected_namespaces.insert(key); - key.first = dm_protocol::kChromeExtensionPolicyType; - for (size_t i = 0; i < arraysize(kExtensions); ++i) { - key.second = kExtensions[i]; - em::PolicyData policy_data; - policy_data.set_policy_type(key.first); - policy_data.set_settings_entity_id(key.second); - expected_responses[key].set_policy_data(policy_data.SerializeAsString()); - policy_response_.mutable_policy_response()->add_response()->CopyFrom( - expected_responses[key]); - expected_namespaces.insert(key); - } - - // Make a policy fetch. - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, - request_context_)) - .WillOnce(service_.SucceedJob(policy_response_)); - EXPECT_CALL(service_, StartJob(dm_protocol::kValueRequestPolicy, "", "", - kDMToken, - dm_protocol::kValueUserAffiliationNone, - client_id_, _)) - .WillOnce(SaveArg<6>(&policy_request_)); - EXPECT_CALL(observer_, OnPolicyFetched(_)); - EXPECT_CALL(status_provider_, OnSubmittedSuccessfully()); - for (size_t i = 0; i < arraysize(kExtensions); ++i) { - client_->AddNamespaceToFetch(PolicyNamespaceKey( - dm_protocol::kChromeExtensionPolicyType, kExtensions[i])); - } - client_->FetchPolicy(); - - // Verify that the request includes the expected namespaces. - ASSERT_TRUE(policy_request_.has_policy_request()); - const em::DevicePolicyRequest& policy_request = - policy_request_.policy_request(); - ASSERT_EQ(static_cast<int>(1 + arraysize(kExtensions)), - policy_request.request_size()); - for (int i = 0; i < policy_request.request_size(); ++i) { - const em::PolicyFetchRequest& fetch_request = policy_request.request(i); - ASSERT_TRUE(fetch_request.has_policy_type()); - std::string entity_id; - if (fetch_request.has_settings_entity_id()) - entity_id = fetch_request.settings_entity_id(); - PolicyNamespaceKey key(fetch_request.policy_type(), entity_id); - EXPECT_EQ(1u, expected_namespaces.erase(key)); - } - EXPECT_TRUE(expected_namespaces.empty()); - - // Verify that the client got all the responses mapped to their namespaces. - for (ResponseMap::iterator it = expected_responses.begin(); - it != expected_responses.end(); ++it) { - const em::PolicyFetchResponse* response = client_->GetPolicyFor(it->first); - ASSERT_TRUE(response); - EXPECT_EQ(it->second.SerializeAsString(), response->SerializeAsString()); - } -} - -TEST_F(CloudPolicyClientTest, UploadCertificate) { - Register(); - - ExpectUploadCertificate(); - EXPECT_CALL(upload_certificate_observer_, OnUploadComplete(true)).Times(1); - CloudPolicyClient::StatusCallback callback = base::Bind( - &MockUploadCertificateObserver::OnUploadComplete, - base::Unretained(&upload_certificate_observer_)); - client_->UploadCertificate(kDeviceCertificate, callback); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); -} - -TEST_F(CloudPolicyClientTest, UploadCertificateEmpty) { - Register(); - - upload_certificate_response_.clear_cert_upload_response(); - ExpectUploadCertificate(); - EXPECT_CALL(upload_certificate_observer_, OnUploadComplete(false)).Times(1); - CloudPolicyClient::StatusCallback callback = base::Bind( - &MockUploadCertificateObserver::OnUploadComplete, - base::Unretained(&upload_certificate_observer_)); - client_->UploadCertificate(kDeviceCertificate, callback); - EXPECT_EQ(DM_STATUS_SUCCESS, client_->status()); -} - -TEST_F(CloudPolicyClientTest, UploadCertificateFailure) { - Register(); - - EXPECT_CALL(upload_certificate_observer_, OnUploadComplete(false)).Times(1); - EXPECT_CALL(service_, - CreateJob(DeviceManagementRequestJob::TYPE_UPLOAD_CERTIFICATE, - request_context_)) - .WillOnce(service_.FailJob(DM_STATUS_REQUEST_FAILED)); - EXPECT_CALL(service_, StartJob(_, _, _, _, _, _, _)); - EXPECT_CALL(observer_, OnClientError(_)); - CloudPolicyClient::StatusCallback callback = base::Bind( - &MockUploadCertificateObserver::OnUploadComplete, - base::Unretained(&upload_certificate_observer_)); - client_->UploadCertificate(kDeviceCertificate, callback); - EXPECT_EQ(DM_STATUS_REQUEST_FAILED, client_->status()); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_constants.cc b/chrome/browser/policy/cloud/cloud_policy_constants.cc deleted file mode 100644 index bc45143..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_constants.cc +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" - -#include "base/command_line.h" -#include "components/policy/core/common/policy_switches.h" - -namespace policy { - -// Constants related to the device management protocol. -namespace dm_protocol { - -// Name constants for URL query parameters. -const char kParamAgent[] = "agent"; -const char kParamAppType[] = "apptype"; -const char kParamDeviceID[] = "deviceid"; -const char kParamDeviceType[] = "devicetype"; -const char kParamOAuthToken[] = "oauth_token"; -const char kParamPlatform[] = "platform"; -const char kParamRequest[] = "request"; -const char kParamUserAffiliation[] = "user_affiliation"; - -// String constants for the device and app type we report to the server. -const char kValueAppType[] = "Chrome"; -const char kValueDeviceType[] = "2"; -const char kValueRequestAutoEnrollment[] = "enterprise_check"; -const char kValueRequestPolicy[] = "policy"; -const char kValueRequestRegister[] = "register"; -const char kValueRequestApiAuthorization[] = "api_authorization"; -const char kValueRequestUnregister[] = "unregister"; -const char kValueRequestUploadCertificate[] = "cert_upload"; -const char kValueUserAffiliationManaged[] = "managed"; -const char kValueUserAffiliationNone[] = "none"; - -const char kChromeDevicePolicyType[] = "google/chromeos/device"; -#if defined(OS_CHROMEOS) -const char kChromeUserPolicyType[] = "google/chromeos/user"; -#elif defined(OS_ANDROID) -const char kChromeUserPolicyType[] = "google/android/user"; -#elif defined(OS_IOS) -const char kChromeUserPolicyType[] = "google/ios/user"; -#else -const char kChromeUserPolicyType[] = "google/chrome/user"; -#endif -const char kChromePublicAccountPolicyType[] = "google/chromeos/publicaccount"; -const char kChromeExtensionPolicyType[] = "google/chrome/extension"; - -} // namespace dm_protocol - -const char* GetChromeUserPolicyType() { -#if defined(OS_ANDROID) || defined(OS_IOS) - CommandLine* command_line = CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kFakeCloudPolicyType)) - return "google/chrome/user"; -#endif - return dm_protocol::kChromeUserPolicyType; -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_constants.h b/chrome/browser/policy/cloud/cloud_policy_constants.h deleted file mode 100644 index aab6f16..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_constants.h +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CONSTANTS_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CONSTANTS_H_ - -#include <string> -#include <utility> - -namespace policy { - -// Constants related to the device management protocol. -namespace dm_protocol { - -// Name extern constants for URL query parameters. -extern const char kParamAgent[]; -extern const char kParamAppType[]; -extern const char kParamDeviceID[]; -extern const char kParamDeviceType[]; -extern const char kParamOAuthToken[]; -extern const char kParamPlatform[]; -extern const char kParamRequest[]; -extern const char kParamUserAffiliation[]; - -// String extern constants for the device and app type we report to the server. -extern const char kValueAppType[]; -extern const char kValueDeviceType[]; -extern const char kValueRequestAutoEnrollment[]; -extern const char kValueRequestPolicy[]; -extern const char kValueRequestRegister[]; -extern const char kValueRequestApiAuthorization[]; -extern const char kValueRequestUnregister[]; -extern const char kValueRequestUploadCertificate[]; -extern const char kValueUserAffiliationManaged[]; -extern const char kValueUserAffiliationNone[]; - -// Policy type strings for the policy_type field in PolicyFetchRequest. -extern const char kChromeDevicePolicyType[]; -extern const char kChromeUserPolicyType[]; -extern const char kChromePublicAccountPolicyType[]; -extern const char kChromeExtensionPolicyType[]; - -// These codes are sent in the |error_code| field of PolicyFetchResponse. -enum PolicyFetchStatus { - POLICY_FETCH_SUCCESS = 200, - POLICY_FETCH_ERROR_NOT_FOUND = 902, -}; - -} // namespace dm_protocol - -// Describes the affiliation of a user w.r.t. the device owner. -enum UserAffiliation { - // User is on the same domain the device was registered with. - USER_AFFILIATION_MANAGED, - // No affiliation between device and user. - USER_AFFILIATION_NONE, -}; - -// Status codes for communication errors with the device management service. -enum DeviceManagementStatus { - // All is good. - DM_STATUS_SUCCESS, - // Request payload invalid. - DM_STATUS_REQUEST_INVALID, - // The HTTP request failed. - DM_STATUS_REQUEST_FAILED, - // The server returned an error code that points to a temporary problem. - DM_STATUS_TEMPORARY_UNAVAILABLE, - // The HTTP request returned a non-success code. - DM_STATUS_HTTP_STATUS_ERROR, - // Response could not be decoded. - DM_STATUS_RESPONSE_DECODING_ERROR, - // Service error: Management not supported. - DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED, - // Service error: Device not found. - DM_STATUS_SERVICE_DEVICE_NOT_FOUND, - // Service error: Device token invalid. - DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID, - // Service error: Activation pending. - DM_STATUS_SERVICE_ACTIVATION_PENDING, - // Service error: The serial number is not valid or not known to the server. - DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER, - // Service error: The device id used for registration is already taken. - DM_STATUS_SERVICE_DEVICE_ID_CONFLICT, - // Service error: The licenses have expired or have been exhausted. - DM_STATUS_SERVICE_MISSING_LICENSES, - // Service error: Policy not found. Error code defined by the DM folks. - DM_STATUS_SERVICE_POLICY_NOT_FOUND = 902, -}; - -// List of modes that the device can be locked into. -enum DeviceMode { - DEVICE_MODE_PENDING, // The device mode is not yet available. - DEVICE_MODE_NOT_SET, // The device is not yet enrolled or owned. - DEVICE_MODE_CONSUMER, // The device is locally owned as consumer - // device. - DEVICE_MODE_ENTERPRISE, // The device is enrolled as an enterprise - // device. - DEVICE_MODE_RETAIL_KIOSK, // The device is enrolled as retail kiosk device. - DEVICE_MODE_CONSUMER_KIOSK, // The device is locally owned as consumer kiosk. -}; - -// A pair that combines a policy fetch type and entity ID. -typedef std::pair<std::string, std::string> PolicyNamespaceKey; - -// Returns the Chrome user policy type to use. This allows overridding the -// default user policy type on Android and iOS for testing purposes. -// TODO(joaodasilva): remove this once the server is ready. -// http://crbug.com/248527 -const char* GetChromeUserPolicyType(); - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CONSTANTS_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_core.cc b/chrome/browser/policy/cloud/cloud_policy_core.cc deleted file mode 100644 index 7697df3..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_core.cc +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_core.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/prefs/pref_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" - -namespace policy { - -CloudPolicyCore::Observer::~Observer() {} - -CloudPolicyCore::CloudPolicyCore( - const PolicyNamespaceKey& key, - CloudPolicyStore* store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner) - : policy_ns_key_(key), - store_(store), - task_runner_(task_runner) {} - -CloudPolicyCore::~CloudPolicyCore() {} - -void CloudPolicyCore::Connect(scoped_ptr<CloudPolicyClient> client) { - CHECK(!client_); - CHECK(client); - client_ = client.Pass(); - service_.reset(new CloudPolicyService(policy_ns_key_, client_.get(), store_)); - FOR_EACH_OBSERVER(Observer, observers_, OnCoreConnected(this)); -} - -void CloudPolicyCore::Disconnect() { - if (client_) - FOR_EACH_OBSERVER(Observer, observers_, OnCoreDisconnecting(this)); - refresh_delay_.reset(); - refresh_scheduler_.reset(); - service_.reset(); - client_.reset(); -} - -void CloudPolicyCore::RefreshSoon() { - if (refresh_scheduler_) - refresh_scheduler_->RefreshSoon(); -} - -void CloudPolicyCore::StartRefreshScheduler() { - if (!refresh_scheduler_) { - refresh_scheduler_.reset( - new CloudPolicyRefreshScheduler(client_.get(), store_, task_runner_)); - UpdateRefreshDelayFromPref(); - FOR_EACH_OBSERVER(Observer, observers_, OnRefreshSchedulerStarted(this)); - } -} - -void CloudPolicyCore::TrackRefreshDelayPref( - PrefService* pref_service, - const std::string& refresh_pref_name) { - refresh_delay_.reset(new IntegerPrefMember()); - refresh_delay_->Init( - refresh_pref_name.c_str(), pref_service, - base::Bind(&CloudPolicyCore::UpdateRefreshDelayFromPref, - base::Unretained(this))); - UpdateRefreshDelayFromPref(); -} - -void CloudPolicyCore::AddObserver(CloudPolicyCore::Observer* observer) { - observers_.AddObserver(observer); -} - -void CloudPolicyCore::RemoveObserver(CloudPolicyCore::Observer* observer) { - observers_.RemoveObserver(observer); -} - -void CloudPolicyCore::UpdateRefreshDelayFromPref() { - if (refresh_scheduler_ && refresh_delay_) - refresh_scheduler_->SetRefreshDelay(refresh_delay_->GetValue()); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_core.h b/chrome/browser/policy/cloud/cloud_policy_core.h deleted file mode 100644 index 48ca11e..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_core.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CORE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CORE_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/prefs/pref_member.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" - -class PrefService; - -namespace base { -class SequencedTaskRunner; -} - -namespace policy { - -class CloudPolicyClient; -class CloudPolicyRefreshScheduler; -class CloudPolicyService; -class CloudPolicyStore; - -// CloudPolicyCore glues together the ingredients that are essential for -// obtaining a fully-functional cloud policy system: CloudPolicyClient and -// CloudPolicyStore, which are responsible for fetching policy from the cloud -// and storing it locally, respectively, as well as a CloudPolicyService -// instance that moves data between the two former components, and -// CloudPolicyRefreshScheduler which triggers periodic refreshes. -class CloudPolicyCore { - public: - // Callbacks for policy core events. - class Observer { - public: - virtual ~Observer(); - - // Called after the core is connected. - virtual void OnCoreConnected(CloudPolicyCore* core) = 0; - - // Called after the refresh scheduler is started. - virtual void OnRefreshSchedulerStarted(CloudPolicyCore* core) = 0; - - // Called before the core is disconnected. - virtual void OnCoreDisconnecting(CloudPolicyCore* core) = 0; - }; - - // |task_runner| is the runner for policy refresh tasks. - CloudPolicyCore(const PolicyNamespaceKey& policy_ns_key, - CloudPolicyStore* store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner); - ~CloudPolicyCore(); - - CloudPolicyClient* client() { return client_.get(); } - const CloudPolicyClient* client() const { return client_.get(); } - - CloudPolicyStore* store() { return store_; } - const CloudPolicyStore* store() const { return store_; } - - CloudPolicyService* service() { return service_.get(); } - const CloudPolicyService* service() const { return service_.get(); } - - CloudPolicyRefreshScheduler* refresh_scheduler() { - return refresh_scheduler_.get(); - } - const CloudPolicyRefreshScheduler* refresh_scheduler() const { - return refresh_scheduler_.get(); - } - - // Initializes the cloud connection. - void Connect(scoped_ptr<CloudPolicyClient> client); - - // Shuts down the cloud connection. - void Disconnect(); - - // Requests a policy refresh to be performed soon. This may apply throttling, - // and the request may not be immediately sent. - void RefreshSoon(); - - // Starts a refresh scheduler in case none is running yet. - void StartRefreshScheduler(); - - // Watches the pref named |refresh_pref_name| in |pref_service| and adjusts - // |refresh_scheduler_|'s refresh delay accordingly. - void TrackRefreshDelayPref(PrefService* pref_service, - const std::string& refresh_pref_name); - - // Registers an observer to be notified of policy core events. - void AddObserver(Observer* observer); - - // Removes the specified observer. - void RemoveObserver(Observer* observer); - - private: - // Updates the refresh scheduler on refresh delay changes. - void UpdateRefreshDelayFromPref(); - - PolicyNamespaceKey policy_ns_key_; - CloudPolicyStore* store_; - scoped_refptr<base::SequencedTaskRunner> task_runner_; - scoped_ptr<CloudPolicyClient> client_; - scoped_ptr<CloudPolicyService> service_; - scoped_ptr<CloudPolicyRefreshScheduler> refresh_scheduler_; - scoped_ptr<IntegerPrefMember> refresh_delay_; - ObserverList<Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyCore); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CORE_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_core_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_core_unittest.cc deleted file mode 100644 index 7d57735..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_core_unittest.cc +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_core.h" - -#include "base/basictypes.h" -#include "base/message_loop/message_loop.h" -#include "base/prefs/pref_registry_simple.h" -#include "base/prefs/testing_pref_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "components/policy/core/common/policy_pref_names.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { - -class CloudPolicyCoreTest : public testing::Test, - public CloudPolicyCore::Observer { - protected: - CloudPolicyCoreTest() - : core_(PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, - std::string()), - &store_, - loop_.message_loop_proxy()), - core_connected_callback_count_(0), - refresh_scheduler_started_callback_count_(0), - core_disconnecting_callback_count_(0), - bad_callback_count_(0) { - prefs_.registry()->RegisterIntegerPref( - policy_prefs::kUserPolicyRefreshRate, - CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs); - core_.AddObserver(this); - } - - virtual ~CloudPolicyCoreTest() { - core_.RemoveObserver(this); - } - - virtual void OnCoreConnected(CloudPolicyCore* core) OVERRIDE { - // Make sure core is connected at callback time. - if (core_.client()) - core_connected_callback_count_++; - else - bad_callback_count_++; - } - - virtual void OnRefreshSchedulerStarted(CloudPolicyCore* core) OVERRIDE { - // Make sure refresh scheduler is started at callback time. - if (core_.refresh_scheduler()) - refresh_scheduler_started_callback_count_++; - else - bad_callback_count_++; - } - - virtual void OnCoreDisconnecting(CloudPolicyCore* core) OVERRIDE { - // Make sure core is still connected at callback time. - if (core_.client()) - core_disconnecting_callback_count_++; - else - bad_callback_count_++; - } - - base::MessageLoop loop_; - - TestingPrefServiceSimple prefs_; - MockCloudPolicyStore store_; - CloudPolicyCore core_; - - int core_connected_callback_count_; - int refresh_scheduler_started_callback_count_; - int core_disconnecting_callback_count_; - int bad_callback_count_; - - private: - DISALLOW_COPY_AND_ASSIGN(CloudPolicyCoreTest); -}; - -TEST_F(CloudPolicyCoreTest, ConnectAndDisconnect) { - EXPECT_TRUE(core_.store()); - EXPECT_FALSE(core_.client()); - EXPECT_FALSE(core_.service()); - EXPECT_FALSE(core_.refresh_scheduler()); - - // Connect() brings up client and service. - core_.Connect(scoped_ptr<CloudPolicyClient>(new MockCloudPolicyClient())); - EXPECT_TRUE(core_.client()); - EXPECT_TRUE(core_.service()); - EXPECT_FALSE(core_.refresh_scheduler()); - EXPECT_EQ(1, core_connected_callback_count_); - EXPECT_EQ(0, refresh_scheduler_started_callback_count_); - EXPECT_EQ(0, core_disconnecting_callback_count_); - - // Disconnect() goes back to no client and service. - core_.Disconnect(); - EXPECT_FALSE(core_.client()); - EXPECT_FALSE(core_.service()); - EXPECT_FALSE(core_.refresh_scheduler()); - EXPECT_EQ(1, core_connected_callback_count_); - EXPECT_EQ(0, refresh_scheduler_started_callback_count_); - EXPECT_EQ(1, core_disconnecting_callback_count_); - - // Calling Disconnect() twice doesn't do bad things. - core_.Disconnect(); - EXPECT_FALSE(core_.client()); - EXPECT_FALSE(core_.service()); - EXPECT_FALSE(core_.refresh_scheduler()); - EXPECT_EQ(1, core_connected_callback_count_); - EXPECT_EQ(0, refresh_scheduler_started_callback_count_); - EXPECT_EQ(1, core_disconnecting_callback_count_); - EXPECT_EQ(0, bad_callback_count_); -} - -TEST_F(CloudPolicyCoreTest, RefreshScheduler) { - EXPECT_FALSE(core_.refresh_scheduler()); - core_.Connect(scoped_ptr<CloudPolicyClient>(new MockCloudPolicyClient())); - core_.StartRefreshScheduler(); - ASSERT_TRUE(core_.refresh_scheduler()); - - int default_refresh_delay = core_.refresh_scheduler()->refresh_delay(); - - const int kRefreshRate = 1000 * 60 * 60; - prefs_.SetInteger(policy_prefs::kUserPolicyRefreshRate, kRefreshRate); - core_.TrackRefreshDelayPref(&prefs_, policy_prefs::kUserPolicyRefreshRate); - EXPECT_EQ(kRefreshRate, core_.refresh_scheduler()->refresh_delay()); - - prefs_.ClearPref(policy_prefs::kUserPolicyRefreshRate); - EXPECT_EQ(default_refresh_delay, core_.refresh_scheduler()->refresh_delay()); - - EXPECT_EQ(1, core_connected_callback_count_); - EXPECT_EQ(1, refresh_scheduler_started_callback_count_); - EXPECT_EQ(0, core_disconnecting_callback_count_); - EXPECT_EQ(0, bad_callback_count_); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator.cc b/chrome/browser/policy/cloud/cloud_policy_invalidator.cc index 733b157..57fdc4c 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator.cc +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator.cc @@ -15,9 +15,9 @@ #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/invalidation/invalidation_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/enterprise_metrics.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" +#include "components/policy/core/common/cloud/enterprise_metrics.h" #include "components/policy/core/common/policy_switches.h" #include "policy/policy_constants.h" #include "sync/notifier/object_id_invalidation_map.h" diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator.h b/chrome/browser/policy/cloud/cloud_policy_invalidator.h index a007a2d..f86016a 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator.h +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator.h @@ -13,8 +13,8 @@ #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" #include "google/cacheinvalidation/include/types.h" #include "sync/internal_api/public/base/invalidation.h" #include "sync/notifier/invalidation_handler.h" diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc index adccdb1..0df14d4 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc @@ -18,14 +18,14 @@ #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/invalidation/fake_invalidation_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" #include "chrome/browser/policy/cloud/cloud_policy_invalidator.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/enterprise_metrics.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" +#include "components/policy/core/common/cloud/enterprise_metrics.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_client.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" #include "components/policy/core/common/policy_types.h" #include "policy/policy_constants.h" #include "sync/notifier/invalidation_util.h" diff --git a/chrome/browser/policy/cloud/cloud_policy_manager.cc b/chrome/browser/policy/cloud/cloud_policy_manager.cc deleted file mode 100644 index e3a01a9..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_manager.cc +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/prefs/pref_service.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_switches.h" -#include "net/url_request/url_request_context_getter.h" - -#if !defined(OS_ANDROID) && !defined(OS_IOS) -#include "chrome/browser/policy/cloud/resource_cache.h" -#endif - -namespace policy { - -CloudPolicyManager::CloudPolicyManager( - const PolicyNamespaceKey& policy_ns_key, - CloudPolicyStore* cloud_policy_store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, - const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) - : core_(policy_ns_key, cloud_policy_store, task_runner), - waiting_for_policy_refresh_(false), - file_task_runner_(file_task_runner), - io_task_runner_(io_task_runner) { - store()->AddObserver(this); - - // If the underlying store is already initialized, publish the loaded - // policy. Otherwise, request a load now. - if (store()->is_initialized()) - CheckAndPublishPolicy(); - else - store()->Load(); -} - -CloudPolicyManager::~CloudPolicyManager() {} - -void CloudPolicyManager::Shutdown() { - component_policy_service_.reset(); - core_.Disconnect(); - store()->RemoveObserver(this); - ConfigurationPolicyProvider::Shutdown(); -} - -bool CloudPolicyManager::IsInitializationComplete(PolicyDomain domain) const { - if (domain == POLICY_DOMAIN_CHROME) - return store()->is_initialized(); - if (ComponentCloudPolicyService::SupportsDomain(domain) && - component_policy_service_) { - return component_policy_service_->is_initialized(); - } - return true; -} - -void CloudPolicyManager::RefreshPolicies() { - if (service()) { - waiting_for_policy_refresh_ = true; - service()->RefreshPolicy( - base::Bind(&CloudPolicyManager::OnRefreshComplete, - base::Unretained(this))); - } else { - OnRefreshComplete(false); - } -} - -void CloudPolicyManager::OnStoreLoaded(CloudPolicyStore* cloud_policy_store) { - DCHECK_EQ(store(), cloud_policy_store); - CheckAndPublishPolicy(); -} - -void CloudPolicyManager::OnStoreError(CloudPolicyStore* cloud_policy_store) { - DCHECK_EQ(store(), cloud_policy_store); - // Publish policy (even though it hasn't changed) in order to signal load - // complete on the ConfigurationPolicyProvider interface. Technically, this - // is only required on the first load, but doesn't hurt in any case. - CheckAndPublishPolicy(); -} - -void CloudPolicyManager::OnComponentCloudPolicyUpdated() { - CheckAndPublishPolicy(); -} - -void CloudPolicyManager::CheckAndPublishPolicy() { - if (IsInitializationComplete(POLICY_DOMAIN_CHROME) && - !waiting_for_policy_refresh_) { - scoped_ptr<PolicyBundle> bundle(new PolicyBundle); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .CopyFrom(store()->policy_map()); - if (component_policy_service_) - bundle->MergeFrom(component_policy_service_->policy()); - UpdatePolicy(bundle.Pass()); - } -} - -void CloudPolicyManager::CreateComponentCloudPolicyService( - const base::FilePath& policy_cache_path, - const scoped_refptr<net::URLRequestContextGetter>& request_context) { -#if !defined(OS_ANDROID) && !defined(OS_IOS) - // Init() must have been called. - DCHECK(schema_registry()); - // Called at most once. - DCHECK(!component_policy_service_); - - if (!CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableComponentCloudPolicy) || - policy_cache_path.empty()) { - return; - } - - // TODO(joaodasilva): Move the |file_task_runner_| to the blocking pool. - // Currently it's not possible because the ComponentCloudPolicyStore is - // NonThreadSafe and doesn't support getting calls from different threads. - scoped_ptr<ResourceCache> resource_cache( - new ResourceCache(policy_cache_path, file_task_runner_)); - component_policy_service_.reset(new ComponentCloudPolicyService( - this, - schema_registry(), - core(), - resource_cache.Pass(), - request_context, - file_task_runner_, - io_task_runner_)); -#endif // !defined(OS_ANDROID) && !defined(OS_IOS) -} - -void CloudPolicyManager::ClearAndDestroyComponentCloudPolicyService() { -#if !defined(OS_ANDROID) && !defined(OS_IOS) - if (component_policy_service_) { - component_policy_service_->ClearCache(); - component_policy_service_.reset(); - } -#endif // !defined(OS_ANDROID) && !defined(OS_IOS) -} - -void CloudPolicyManager::OnRefreshComplete(bool success) { - waiting_for_policy_refresh_ = false; - CheckAndPublishPolicy(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_manager.h b/chrome/browser/policy/cloud/cloud_policy_manager.h deleted file mode 100644 index 8ae1614..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_manager.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_MANAGER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_MANAGER_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/prefs/pref_member.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/component_cloud_policy_service.h" -#include "components/policy/core/common/configuration_policy_provider.h" - -namespace base { -class FilePath; -class SequencedTaskRunner; -} - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -// CloudPolicyManager is the main switching central between cloud policy and the -// upper layers of the policy stack. It wires up a CloudPolicyCore to the -// ConfigurationPolicyProvider interface. -// -// This class contains the base functionality, there are subclasses that add -// functionality specific to user-level and device-level cloud policy, such as -// blocking on initial user policy fetch or device enrollment. -class CloudPolicyManager : public ConfigurationPolicyProvider, - public CloudPolicyStore::Observer, - public ComponentCloudPolicyService::Delegate { - public: - // |task_runner| is the runner for policy refresh tasks. - // |file_task_runner| is used for file operations. Currently this must be the - // FILE BrowserThread. - // |io_task_runner| is used for network IO. Currently this must be the IO - // BrowserThread. - CloudPolicyManager( - const PolicyNamespaceKey& policy_ns_key, - CloudPolicyStore* cloud_policy_store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, - const scoped_refptr<base::SequencedTaskRunner>& io_task_runner); - virtual ~CloudPolicyManager(); - - CloudPolicyCore* core() { return &core_; } - const CloudPolicyCore* core() const { return &core_; } - - // ConfigurationPolicyProvider: - virtual void Shutdown() OVERRIDE; - virtual bool IsInitializationComplete(PolicyDomain domain) const OVERRIDE; - virtual void RefreshPolicies() OVERRIDE; - - // CloudPolicyStore::Observer: - virtual void OnStoreLoaded(CloudPolicyStore* cloud_policy_store) OVERRIDE; - virtual void OnStoreError(CloudPolicyStore* cloud_policy_store) OVERRIDE; - - // ComponentCloudPolicyService::Delegate: - virtual void OnComponentCloudPolicyUpdated() OVERRIDE; - - protected: - // Check whether fully initialized and if so, publish policy by calling - // ConfigurationPolicyStore::UpdatePolicy(). - void CheckAndPublishPolicy(); - - void CreateComponentCloudPolicyService( - const base::FilePath& policy_cache_path, - const scoped_refptr<net::URLRequestContextGetter>& request_context); - - void ClearAndDestroyComponentCloudPolicyService(); - - // Convenience accessors to core() components. - CloudPolicyClient* client() { return core_.client(); } - const CloudPolicyClient* client() const { return core_.client(); } - CloudPolicyStore* store() { return core_.store(); } - const CloudPolicyStore* store() const { return core_.store(); } - CloudPolicyService* service() { return core_.service(); } - const CloudPolicyService* service() const { return core_.service(); } - ComponentCloudPolicyService* component_policy_service() const { - return component_policy_service_.get(); - } - - private: - // Completion handler for policy refresh operations. - void OnRefreshComplete(bool success); - - CloudPolicyCore core_; - scoped_ptr<ComponentCloudPolicyService> component_policy_service_; - - // Whether there's a policy refresh operation pending, in which case all - // policy update notifications are deferred until after it completes. - bool waiting_for_policy_refresh_; - - scoped_refptr<base::SequencedTaskRunner> file_task_runner_; - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyManager); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_MANAGER_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc index 5146b6e..c887c2c 100644 --- a/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc @@ -7,15 +7,15 @@ #include "base/run_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" #include "chrome/browser/policy/cloud/test_request_interceptor.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "chrome/browser/policy/test/policy_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_client.h" +#include "components/policy/core/common/policy_test_utils.h" #include "content/public/browser/browser_thread.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/policy/cloud/cloud_policy_manager_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_manager_unittest.cc deleted file mode 100644 index 5e871ff..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_manager_unittest.cc +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "components/policy/core/common/configuration_policy_provider_test.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/mock_configuration_policy_provider.h" -#include "components/policy/core/common/schema_registry.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::Mock; -using testing::_; - -namespace em = enterprise_management; - -namespace policy { -namespace { - -class TestHarness : public PolicyProviderTestHarness { - public: - explicit TestHarness(PolicyLevel level); - virtual ~TestHarness(); - - virtual void SetUp() OVERRIDE; - - virtual ConfigurationPolicyProvider* CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE; - - virtual void InstallEmptyPolicy() OVERRIDE; - virtual void InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) OVERRIDE; - virtual void InstallIntegerPolicy(const std::string& policy_name, - int policy_value) OVERRIDE; - virtual void InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) OVERRIDE; - virtual void InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) OVERRIDE; - virtual void InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) OVERRIDE; - - // Creates harnesses for mandatory and recommended levels, respectively. - static PolicyProviderTestHarness* CreateMandatory(); - static PolicyProviderTestHarness* CreateRecommended(); - - private: - MockCloudPolicyStore store_; - - DISALLOW_COPY_AND_ASSIGN(TestHarness); -}; - -TestHarness::TestHarness(PolicyLevel level) - : PolicyProviderTestHarness(level, POLICY_SCOPE_USER) {} - -TestHarness::~TestHarness() {} - -void TestHarness::SetUp() {} - -ConfigurationPolicyProvider* TestHarness::CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) { - // Create and initialize the store. - store_.NotifyStoreLoaded(); - ConfigurationPolicyProvider* provider = new CloudPolicyManager( - PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, std::string()), - &store_, - task_runner, - task_runner, - task_runner); - Mock::VerifyAndClearExpectations(&store_); - return provider; -} - -void TestHarness::InstallEmptyPolicy() {} - -void TestHarness::InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) { - store_.policy_map_.Set(policy_name, policy_level(), policy_scope(), - base::Value::CreateStringValue(policy_value), NULL); -} - -void TestHarness::InstallIntegerPolicy(const std::string& policy_name, - int policy_value) { - store_.policy_map_.Set(policy_name, policy_level(), policy_scope(), - base::Value::CreateIntegerValue(policy_value), NULL); -} - -void TestHarness::InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) { - store_.policy_map_.Set(policy_name, policy_level(), policy_scope(), - base::Value::CreateBooleanValue(policy_value), NULL); -} - -void TestHarness::InstallStringListPolicy(const std::string& policy_name, - const base::ListValue* policy_value) { - store_.policy_map_.Set(policy_name, policy_level(), policy_scope(), - policy_value->DeepCopy(), NULL); -} - -void TestHarness::InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) { - store_.policy_map_.Set(policy_name, policy_level(), policy_scope(), - policy_value->DeepCopy(), NULL); -} - -// static -PolicyProviderTestHarness* TestHarness::CreateMandatory() { - return new TestHarness(POLICY_LEVEL_MANDATORY); -} - -// static -PolicyProviderTestHarness* TestHarness::CreateRecommended() { - return new TestHarness(POLICY_LEVEL_RECOMMENDED); -} - -// Instantiate abstract test case for basic policy reading tests. -INSTANTIATE_TEST_CASE_P( - UserCloudPolicyManagerProviderTest, - ConfigurationPolicyProviderTest, - testing::Values(TestHarness::CreateMandatory, - TestHarness::CreateRecommended)); - -class TestCloudPolicyManager : public CloudPolicyManager { - public: - TestCloudPolicyManager( - CloudPolicyStore* store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner) - : CloudPolicyManager(PolicyNamespaceKey( - dm_protocol::kChromeUserPolicyType, - std::string()), - store, - task_runner, - task_runner, - task_runner) {} - virtual ~TestCloudPolicyManager() {} - - // Publish the protected members for testing. - using CloudPolicyManager::client; - using CloudPolicyManager::store; - using CloudPolicyManager::service; - using CloudPolicyManager::CheckAndPublishPolicy; - - private: - DISALLOW_COPY_AND_ASSIGN(TestCloudPolicyManager); -}; - -MATCHER_P(ProtoMatches, proto, "") { - return arg.SerializePartialAsString() == proto.SerializePartialAsString(); -} - -class CloudPolicyManagerTest : public testing::Test { - protected: - CloudPolicyManagerTest() - : policy_ns_key_(dm_protocol::kChromeUserPolicyType, std::string()) {} - - virtual void SetUp() OVERRIDE { - // Set up a policy map for testing. - policy_map_.Set("key", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("value"), NULL); - expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .CopyFrom(policy_map_); - - policy_.payload().mutable_passwordmanagerenabled()->set_value(false); - policy_.Build(); - - EXPECT_CALL(store_, Load()); - manager_.reset(new TestCloudPolicyManager(&store_, - loop_.message_loop_proxy())); - manager_->Init(&schema_registry_); - Mock::VerifyAndClearExpectations(&store_); - manager_->AddObserver(&observer_); - } - - virtual void TearDown() OVERRIDE { - manager_->RemoveObserver(&observer_); - manager_->Shutdown(); - } - - // Required by the refresh scheduler that's created by the manager. - base::MessageLoop loop_; - - // Testing policy. - const PolicyNamespaceKey policy_ns_key_; - UserPolicyBuilder policy_; - PolicyMap policy_map_; - PolicyBundle expected_bundle_; - - // Policy infrastructure. - SchemaRegistry schema_registry_; - MockConfigurationPolicyObserver observer_; - MockCloudPolicyStore store_; - scoped_ptr<TestCloudPolicyManager> manager_; - - private: - DISALLOW_COPY_AND_ASSIGN(CloudPolicyManagerTest); -}; - -TEST_F(CloudPolicyManagerTest, InitAndShutdown) { - PolicyBundle empty_bundle; - EXPECT_TRUE(empty_bundle.Equals(manager_->policies())); - EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - - EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0); - manager_->CheckAndPublishPolicy(); - Mock::VerifyAndClearExpectations(&observer_); - - store_.policy_map_.CopyFrom(policy_map_); - store_.policy_.reset(new em::PolicyData(policy_.policy_data())); - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(expected_bundle_.Equals(manager_->policies())); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - - MockCloudPolicyClient* client = new MockCloudPolicyClient(); - EXPECT_CALL(*client, SetupRegistration(_, _)); - manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client)); - Mock::VerifyAndClearExpectations(client); - EXPECT_TRUE(manager_->client()); - EXPECT_TRUE(manager_->service()); - - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - manager_->CheckAndPublishPolicy(); - Mock::VerifyAndClearExpectations(&observer_); - - manager_->core()->Disconnect(); - EXPECT_FALSE(manager_->client()); - EXPECT_FALSE(manager_->service()); -} - -TEST_F(CloudPolicyManagerTest, RegistrationAndFetch) { - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - - MockCloudPolicyClient* client = new MockCloudPolicyClient(); - manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client)); - - client->SetDMToken(policy_.policy_data().request_token()); - client->NotifyRegistrationStateChanged(); - - client->SetPolicy(policy_ns_key_, policy_.policy()); - EXPECT_CALL(store_, Store(ProtoMatches(policy_.policy()))); - client->NotifyPolicyFetched(); - Mock::VerifyAndClearExpectations(&store_); - - store_.policy_map_.CopyFrom(policy_map_); - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(expected_bundle_.Equals(manager_->policies())); -} - -TEST_F(CloudPolicyManagerTest, Update) { - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - PolicyBundle empty_bundle; - EXPECT_TRUE(empty_bundle.Equals(manager_->policies())); - - store_.policy_map_.CopyFrom(policy_map_); - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - EXPECT_TRUE(expected_bundle_.Equals(manager_->policies())); - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); -} - -TEST_F(CloudPolicyManagerTest, RefreshNotRegistered) { - MockCloudPolicyClient* client = new MockCloudPolicyClient(); - manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client)); - - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - - // A refresh on a non-registered store should not block. - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - manager_->RefreshPolicies(); - Mock::VerifyAndClearExpectations(&observer_); -} - -TEST_F(CloudPolicyManagerTest, RefreshSuccessful) { - MockCloudPolicyClient* client = new MockCloudPolicyClient(); - manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client)); - - // Simulate a store load. - store_.policy_.reset(new em::PolicyData(policy_.policy_data())); - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - EXPECT_CALL(*client, SetupRegistration(_, _)); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(client); - Mock::VerifyAndClearExpectations(&observer_); - - // Acknowledge registration. - client->SetDMToken(policy_.policy_data().request_token()); - - // Start a refresh. - EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0); - EXPECT_CALL(*client, FetchPolicy()); - manager_->RefreshPolicies(); - Mock::VerifyAndClearExpectations(client); - Mock::VerifyAndClearExpectations(&observer_); - store_.policy_map_.CopyFrom(policy_map_); - - // A stray reload should be suppressed until the refresh completes. - EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0); - store_.NotifyStoreLoaded(); - Mock::VerifyAndClearExpectations(&observer_); - - // Respond to the policy fetch, which should trigger a write to |store_|. - EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0); - EXPECT_CALL(store_, Store(_)); - client->SetPolicy(policy_ns_key_, policy_.policy()); - client->NotifyPolicyFetched(); - Mock::VerifyAndClearExpectations(&observer_); - Mock::VerifyAndClearExpectations(&store_); - - // The load notification from |store_| should trigger the policy update. - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreLoaded(); - EXPECT_TRUE(expected_bundle_.Equals(manager_->policies())); - Mock::VerifyAndClearExpectations(&observer_); -} - -TEST_F(CloudPolicyManagerTest, SignalOnError) { - // Simulate a failed load and verify that it triggers OnUpdatePolicy(). - store_.policy_.reset(new em::PolicyData(policy_.policy_data())); - EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); - store_.NotifyStoreError(); - Mock::VerifyAndClearExpectations(&observer_); - - EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); -} - -} // namespace -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.cc b/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.cc deleted file mode 100644 index aaf1c29..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.cc +++ /dev/null @@ -1,375 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" - -#include <algorithm> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/command_line.h" -#include "base/memory/scoped_ptr.h" -#include "base/metrics/histogram.h" -#include "base/sequenced_task_runner.h" -#include "base/time/default_tick_clock.h" -#include "base/time/tick_clock.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "components/policy/core/common/policy_switches.h" - -namespace policy { - -namespace { - -// The maximum rate at which to refresh policies. -const size_t kMaxRefreshesPerHour = 5; - -// The maximum time to wait for the invalidations service to become available -// before starting to issue requests. -const int kWaitForInvalidationsTimeoutSeconds = 5; - -} // namespace - -#if defined(OS_ANDROID) - -const int64 CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs = - 24 * 60 * 60 * 1000; // 1 day. -const int64 CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs = - 24 * 60 * 60 * 1000; // 1 day. -// Delay for periodic refreshes when the invalidations service is available, -// in milliseconds. -// TODO(joaodasilva): increase this value once we're confident that the -// invalidations channel works as expected. -const int64 CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs = - 24 * 60 * 60 * 1000; // 1 day. -const int64 CloudPolicyRefreshScheduler::kInitialErrorRetryDelayMs = - 5 * 60 * 1000; // 5 minutes. -const int64 CloudPolicyRefreshScheduler::kRefreshDelayMinMs = - 30 * 60 * 1000; // 30 minutes. -const int64 CloudPolicyRefreshScheduler::kRefreshDelayMaxMs = - 7 * 24 * 60 * 60 * 1000; // 1 week. - -#else - -const int64 CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs = - 3 * 60 * 60 * 1000; // 3 hours. -const int64 CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs = - 24 * 60 * 60 * 1000; // 1 day. -// Delay for periodic refreshes when the invalidations service is available, -// in milliseconds. -// TODO(joaodasilva): increase this value once we're confident that the -// invalidations channel works as expected. -const int64 CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs = - 3 * 60 * 60 * 1000; // 3 hours. -const int64 CloudPolicyRefreshScheduler::kInitialErrorRetryDelayMs = - 5 * 60 * 1000; // 5 minutes. -const int64 CloudPolicyRefreshScheduler::kRefreshDelayMinMs = - 30 * 60 * 1000; // 30 minutes. -const int64 CloudPolicyRefreshScheduler::kRefreshDelayMaxMs = - 24 * 60 * 60 * 1000; // 1 day. - -#endif - -CloudPolicyRefreshScheduler::CloudPolicyRefreshScheduler( - CloudPolicyClient* client, - CloudPolicyStore* store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner) - : client_(client), - store_(store), - task_runner_(task_runner), - error_retry_delay_ms_(kInitialErrorRetryDelayMs), - refresh_delay_ms_(kDefaultRefreshDelayMs), - rate_limiter_(kMaxRefreshesPerHour, - base::TimeDelta::FromHours(1), - base::Bind(&CloudPolicyRefreshScheduler::RefreshNow, - base::Unretained(this)), - task_runner_, - scoped_ptr<base::TickClock>(new base::DefaultTickClock())), - invalidations_available_(false), - creation_time_(base::Time::NowFromSystemTime()) { - client_->AddObserver(this); - store_->AddObserver(this); - net::NetworkChangeNotifier::AddIPAddressObserver(this); - - UpdateLastRefreshFromPolicy(); - - // Give some time for the invalidation service to become available before the - // first refresh if there is already policy present. - if (store->has_policy()) - WaitForInvalidationService(); - else - ScheduleRefresh(); -} - -CloudPolicyRefreshScheduler::~CloudPolicyRefreshScheduler() { - store_->RemoveObserver(this); - client_->RemoveObserver(this); - net::NetworkChangeNotifier::RemoveIPAddressObserver(this); -} - -void CloudPolicyRefreshScheduler::SetRefreshDelay(int64 refresh_delay) { - refresh_delay_ms_ = std::min(std::max(refresh_delay, kRefreshDelayMinMs), - kRefreshDelayMaxMs); - ScheduleRefresh(); -} - -void CloudPolicyRefreshScheduler::RefreshSoon() { - // An external consumer needs a policy update now (e.g. a new extension, or - // the InvalidationService received a policy invalidation), so don't wait - // before fetching anymore. - wait_for_invalidations_timeout_callback_.Cancel(); - rate_limiter_.PostRequest(); -} - -void CloudPolicyRefreshScheduler::SetInvalidationServiceAvailability( - bool is_available) { - if (!creation_time_.is_null()) { - base::TimeDelta elapsed = base::Time::NowFromSystemTime() - creation_time_; - UMA_HISTOGRAM_MEDIUM_TIMES("Enterprise.PolicyInvalidationsStartupTime", - elapsed); - creation_time_ = base::Time(); - } - - if (is_available == invalidations_available_) { - // No change in state. If we're currently WaitingForInvalidationService - // then the timeout task will eventually execute and trigger a reschedule; - // let the InvalidationService keep retrying until that happens. - return; - } - - wait_for_invalidations_timeout_callback_.Cancel(); - invalidations_available_ = is_available; - - // Schedule a refresh since the refresh delay has been updated; however, allow - // some time for the invalidation service to update. If it is now online, the - // wait allows pending invalidations to be delivered. If it is now offline, - // then the wait allows for the service to recover from transient failure - // before falling back on the polling behavior. - WaitForInvalidationService(); -} - -void CloudPolicyRefreshScheduler::OnPolicyFetched(CloudPolicyClient* client) { - error_retry_delay_ms_ = kInitialErrorRetryDelayMs; - - // Schedule the next refresh. - last_refresh_ = base::Time::NowFromSystemTime(); - ScheduleRefresh(); -} - -void CloudPolicyRefreshScheduler::OnRegistrationStateChanged( - CloudPolicyClient* client) { - error_retry_delay_ms_ = kInitialErrorRetryDelayMs; - - // The client might have registered, so trigger an immediate refresh. - RefreshNow(); -} - -void CloudPolicyRefreshScheduler::OnClientError(CloudPolicyClient* client) { - // Save the status for below. - DeviceManagementStatus status = client_->status(); - - // Schedule an error retry if applicable. - last_refresh_ = base::Time::NowFromSystemTime(); - ScheduleRefresh(); - - // Update the retry delay. - if (client->is_registered() && - (status == DM_STATUS_REQUEST_FAILED || - status == DM_STATUS_TEMPORARY_UNAVAILABLE)) { - error_retry_delay_ms_ = std::min(error_retry_delay_ms_ * 2, - refresh_delay_ms_); - } else { - error_retry_delay_ms_ = kInitialErrorRetryDelayMs; - } -} - -void CloudPolicyRefreshScheduler::OnStoreLoaded(CloudPolicyStore* store) { - UpdateLastRefreshFromPolicy(); - - // Re-schedule the next refresh in case the is_managed bit changed. - ScheduleRefresh(); -} - -void CloudPolicyRefreshScheduler::OnStoreError(CloudPolicyStore* store) { - // If |store_| fails, the is_managed bit that it provides may become stale. - // The best guess in that situation is to assume is_managed didn't change and - // continue using the stale information. Thus, no specific response to a store - // error is required. NB: Changes to is_managed fire OnStoreLoaded(). -} - -void CloudPolicyRefreshScheduler::OnIPAddressChanged() { - if (client_->status() == DM_STATUS_REQUEST_FAILED) - RefreshSoon(); -} - -void CloudPolicyRefreshScheduler::UpdateLastRefreshFromPolicy() { - if (!last_refresh_.is_null()) - return; - - // If the client has already fetched policy, assume that happened recently. If - // that assumption ever breaks, the proper thing to do probably is to move the - // |last_refresh_| bookkeeping to CloudPolicyClient. - if (!client_->responses().empty()) { - last_refresh_ = base::Time::NowFromSystemTime(); - return; - } - -#if defined(OS_ANDROID) - // Refreshing on Android: - // - if no user is signed-in then the |client_| is never registered and - // nothing happens here. - // - if the user is signed-in but isn't enterprise then the |client_| is - // never registered and nothing happens here. - // - if the user is signed-in but isn't registered for policy yet then the - // |client_| isn't registered either; the UserPolicySigninService will try - // to register, and OnRegistrationStateChanged() will be invoked later. - // - if the client is signed-in and has policy then its timestamp is used to - // determine when to perform the next fetch, which will be once the cached - // version is considered "old enough". - // - // If there is an old policy cache then a fetch will be performed "soon"; if - // that fetch fails then a retry is attempted after a delay, with exponential - // backoff. If those fetches keep failing then the cached timestamp is *not* - // updated, and another fetch (and subsequent retries) will be attempted - // again on the next startup. - // - // But if the cached policy is considered fresh enough then we try to avoid - // fetching again on startup; the Android logic differs from the desktop in - // this aspect. - if (store_->has_policy() && store_->policy()->has_timestamp()) { - last_refresh_ = - base::Time::UnixEpoch() + - base::TimeDelta::FromMilliseconds(store_->policy()->timestamp()); - } -#else - // If there is a cached non-managed response, make sure to only re-query the - // server after kUnmanagedRefreshDelayMs. NB: For existing policy, an - // immediate refresh is intentional. - if (store_->has_policy() && store_->policy()->has_timestamp() && - !store_->is_managed()) { - last_refresh_ = - base::Time::UnixEpoch() + - base::TimeDelta::FromMilliseconds(store_->policy()->timestamp()); - } -#endif -} - -void CloudPolicyRefreshScheduler::RefreshNow() { - last_refresh_ = base::Time(); - ScheduleRefresh(); -} - -void CloudPolicyRefreshScheduler::ScheduleRefresh() { - // If the client isn't registered, there is nothing to do. - if (!client_->is_registered()) { - refresh_callback_.Cancel(); - return; - } - - // Don't schedule anything yet if we're still waiting for the invalidations - // service. - if (WaitingForInvalidationService()) - return; - - // If policy invalidations are available then periodic updates are done at - // a much lower rate; otherwise use the |refresh_delay_ms_| value. - int64 refresh_delay_ms = - invalidations_available_ ? kWithInvalidationsRefreshDelayMs - : refresh_delay_ms_; - - // If there is a registration, go by the client's status. That will tell us - // what the appropriate refresh delay should be. - switch (client_->status()) { - case DM_STATUS_SUCCESS: - if (store_->is_managed()) - RefreshAfter(refresh_delay_ms); - else - RefreshAfter(kUnmanagedRefreshDelayMs); - return; - case DM_STATUS_SERVICE_ACTIVATION_PENDING: - case DM_STATUS_SERVICE_POLICY_NOT_FOUND: - RefreshAfter(refresh_delay_ms); - return; - case DM_STATUS_REQUEST_FAILED: - case DM_STATUS_TEMPORARY_UNAVAILABLE: - RefreshAfter(error_retry_delay_ms_); - return; - case DM_STATUS_REQUEST_INVALID: - case DM_STATUS_HTTP_STATUS_ERROR: - case DM_STATUS_RESPONSE_DECODING_ERROR: - case DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED: - RefreshAfter(kUnmanagedRefreshDelayMs); - return; - case DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID: - case DM_STATUS_SERVICE_DEVICE_NOT_FOUND: - case DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER: - case DM_STATUS_SERVICE_DEVICE_ID_CONFLICT: - case DM_STATUS_SERVICE_MISSING_LICENSES: - // Need a re-registration, no use in retrying. - refresh_callback_.Cancel(); - return; - } - - NOTREACHED() << "Invalid client status " << client_->status(); - RefreshAfter(kUnmanagedRefreshDelayMs); -} - -void CloudPolicyRefreshScheduler::PerformRefresh() { - if (client_->is_registered()) { - // Update |last_refresh_| so another fetch isn't triggered inadvertently. - last_refresh_ = base::Time::NowFromSystemTime(); - - // The result of this operation will be reported through a callback, at - // which point the next refresh will be scheduled. - client_->FetchPolicy(); - return; - } - - // This should never happen, as the registration change should have been - // handled via OnRegistrationStateChanged(). - NOTREACHED(); -} - -void CloudPolicyRefreshScheduler::RefreshAfter(int delta_ms) { - base::TimeDelta delta(base::TimeDelta::FromMilliseconds(delta_ms)); - refresh_callback_.Cancel(); - - // Schedule the callback. - base::TimeDelta delay = - std::max((last_refresh_ + delta) - base::Time::NowFromSystemTime(), - base::TimeDelta()); - refresh_callback_.Reset( - base::Bind(&CloudPolicyRefreshScheduler::PerformRefresh, - base::Unretained(this))); - task_runner_->PostDelayedTask(FROM_HERE, refresh_callback_.callback(), delay); -} - -void CloudPolicyRefreshScheduler::WaitForInvalidationService() { - DCHECK(!WaitingForInvalidationService()); - wait_for_invalidations_timeout_callback_.Reset( - base::Bind( - &CloudPolicyRefreshScheduler::OnWaitForInvalidationServiceTimeout, - base::Unretained(this))); - base::TimeDelta delay = - base::TimeDelta::FromSeconds(kWaitForInvalidationsTimeoutSeconds); - // Do not wait for the invalidation service if the feature is disabled. - if (CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDisableCloudPolicyPush)) { - delay = base::TimeDelta(); - } - task_runner_->PostDelayedTask( - FROM_HERE, - wait_for_invalidations_timeout_callback_.callback(), - delay); -} - -void CloudPolicyRefreshScheduler::OnWaitForInvalidationServiceTimeout() { - wait_for_invalidations_timeout_callback_.Cancel(); - ScheduleRefresh(); -} - -bool CloudPolicyRefreshScheduler::WaitingForInvalidationService() const { - return !wait_for_invalidations_timeout_callback_.IsCancelled(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h b/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h deleted file mode 100644 index a3d121b..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_REFRESH_SCHEDULER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_REFRESH_SCHEDULER_H_ - -#include "base/basictypes.h" -#include "base/cancelable_callback.h" -#include "base/memory/ref_counted.h" -#include "base/time/time.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/rate_limiter.h" -#include "net/base/network_change_notifier.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace policy { - -// Observes CloudPolicyClient and CloudPolicyStore to trigger periodic policy -// fetches and issue retries on error conditions. -class CloudPolicyRefreshScheduler - : public CloudPolicyClient::Observer, - public CloudPolicyStore::Observer, - public net::NetworkChangeNotifier::IPAddressObserver { - public: - // Refresh constants. - static const int64 kDefaultRefreshDelayMs; - static const int64 kUnmanagedRefreshDelayMs; - static const int64 kWithInvalidationsRefreshDelayMs; - static const int64 kInitialErrorRetryDelayMs; - - // Refresh delay bounds. - static const int64 kRefreshDelayMinMs; - static const int64 kRefreshDelayMaxMs; - - // |client| and |store| pointers must stay valid throughout the - // lifetime of CloudPolicyRefreshScheduler. - CloudPolicyRefreshScheduler( - CloudPolicyClient* client, - CloudPolicyStore* store, - const scoped_refptr<base::SequencedTaskRunner>& task_runner); - virtual ~CloudPolicyRefreshScheduler(); - - base::Time last_refresh() const { return last_refresh_; } - int64 refresh_delay() const { return refresh_delay_ms_; } - - // Sets the refresh delay to |refresh_delay| (subject to min/max clamping). - void SetRefreshDelay(int64 refresh_delay); - - // Requests a policy refresh to be performed soon. This may apply throttling, - // and the request may not be immediately sent. - void RefreshSoon(); - - // The refresh scheduler starts by assuming that invalidations are not - // available. This call can be used to signal whether the invalidations - // service is available or not, and can be called multiple times. - // When the invalidations service is available then the refresh rate is much - // lower. - void SetInvalidationServiceAvailability(bool is_available); - - // Whether the invalidations service is available and receiving notifications - // of policy updates. - bool invalidations_available() { - return invalidations_available_; - } - - // CloudPolicyClient::Observer: - virtual void OnPolicyFetched(CloudPolicyClient* client) OVERRIDE; - virtual void OnRegistrationStateChanged(CloudPolicyClient* client) OVERRIDE; - virtual void OnClientError(CloudPolicyClient* client) OVERRIDE; - - // CloudPolicyStore::Observer: - virtual void OnStoreLoaded(CloudPolicyStore* store) OVERRIDE; - virtual void OnStoreError(CloudPolicyStore* store) OVERRIDE; - - // net::NetworkChangeNotifier::IPAddressObserver: - virtual void OnIPAddressChanged() OVERRIDE; - - private: - // Initializes |last_refresh_| to the policy timestamp from |store_| in case - // there is policy present that indicates this client is not managed. This - // results in policy fetches only to occur after the entire unmanaged refresh - // delay expires, even over restarts. For managed clients, we want to trigger - // a refresh on every restart. - void UpdateLastRefreshFromPolicy(); - - // Schedules a refresh to be performed immediately. - void RefreshNow(); - - // Evaluates when the next refresh is pending and updates the callback to - // execute that refresh at the appropriate time. - void ScheduleRefresh(); - - // Triggers a policy refresh. - void PerformRefresh(); - - // Schedules a policy refresh to happen after |delta_ms| milliseconds, - // relative to |last_refresh_|. - void RefreshAfter(int delta_ms); - - // Sets the |wait_for_invalidations_timeout_callback_| and schedules it. - void WaitForInvalidationService(); - - // Callback for |wait_for_invalidations_timeout_callback_|. - void OnWaitForInvalidationServiceTimeout(); - - // Returns true if the refresh scheduler is currently waiting for the - // availability of the invalidations service. - bool WaitingForInvalidationService() const; - - CloudPolicyClient* client_; - CloudPolicyStore* store_; - - // For scheduling delayed tasks. - const scoped_refptr<base::SequencedTaskRunner> task_runner_; - - // The delayed refresh callback. - base::CancelableClosure refresh_callback_; - - // The last time a refresh callback completed. - base::Time last_refresh_; - - // Error retry delay in milliseconds. - int64 error_retry_delay_ms_; - - // The refresh delay. - int64 refresh_delay_ms_; - - // Used to limit the rate at which refreshes are scheduled. - RateLimiter rate_limiter_; - - // Whether the invalidations service is available and receiving notifications - // of policy updates. - bool invalidations_available_; - - // The refresh scheduler waits some seconds for the invalidations service - // before starting to issue refresh requests. If the invalidations service - // doesn't become available during this time then the refresh scheduler will - // use the polling refresh rate. - base::CancelableClosure wait_for_invalidations_timeout_callback_; - - // Used to measure how long it took for the invalidations service to report - // its initial status. - base::Time creation_time_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyRefreshScheduler); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_REFRESH_SCHEDULER_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler_unittest.cc deleted file mode 100644 index 85a256d..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_refresh_scheduler_unittest.cc +++ /dev/null @@ -1,493 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/test/test_simple_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "policy/policy_constants.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace em = enterprise_management; - -using testing::Mock; - -namespace policy { - -namespace { - -const int64 kPolicyRefreshRate = 4 * 60 * 60 * 1000; - -const int64 kInitialCacheAgeMinutes = 1; - -} // namespace - -class CloudPolicyRefreshSchedulerTest : public testing::Test { - protected: - CloudPolicyRefreshSchedulerTest() - : task_runner_(new base::TestSimpleTaskRunner()), - network_change_notifier_(net::NetworkChangeNotifier::CreateMock()) {} - - virtual void SetUp() OVERRIDE { - client_.SetDMToken("token"); - - // Set up the protobuf timestamp to be one minute in the past. Since the - // protobuf field only has millisecond precision, we convert the actual - // value back to get a millisecond-clamped time stamp for the checks below. - store_.policy_.reset(new em::PolicyData()); - base::Time now = base::Time::NowFromSystemTime(); - base::TimeDelta initial_age = - base::TimeDelta::FromMinutes(kInitialCacheAgeMinutes); - store_.policy_->set_timestamp( - ((now - initial_age) - base::Time::UnixEpoch()).InMilliseconds()); - last_update_ = - base::Time::UnixEpoch() + - base::TimeDelta::FromMilliseconds(store_.policy_->timestamp()); - } - - CloudPolicyRefreshScheduler* CreateRefreshScheduler() { - EXPECT_EQ(0u, task_runner_->GetPendingTasks().size()); - CloudPolicyRefreshScheduler* scheduler = - new CloudPolicyRefreshScheduler(&client_, &store_, task_runner_); - scheduler->SetRefreshDelay(kPolicyRefreshRate); - // If the store has policy, run the wait-for-invalidations timeout task. - if (store_.has_policy()) { - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - task_runner_->RunPendingTasks(); - } - return scheduler; - } - - void NotifyIPAddressChanged() { - net::NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); - loop_.RunUntilIdle(); - } - - base::TimeDelta GetLastDelay() const { - const std::deque<base::TestPendingTask>& pending_tasks = - task_runner_->GetPendingTasks(); - return - pending_tasks.empty() ? base::TimeDelta() : pending_tasks.back().delay; - } - - void CheckTiming(int64 expected_delay_ms) const { - CheckTimingWithAge(base::TimeDelta::FromMilliseconds(expected_delay_ms), - base::TimeDelta()); - } - - // Checks that the latest refresh scheduled used an offset of - // |offset_from_last_refresh| from the time of the previous refresh. - // |cache_age| is how old the cache was when the refresh was issued. - void CheckTimingWithAge(const base::TimeDelta& offset_from_last_refresh, - const base::TimeDelta& cache_age) const { - EXPECT_FALSE(task_runner_->GetPendingTasks().empty()); - base::Time now(base::Time::NowFromSystemTime()); - // |last_update_| was updated and then a refresh was scheduled at time S, - // so |last_update_| is a bit before that. - // Now is a bit later, N. - // GetLastDelay() + S is the time when the refresh will run, T. - // |cache_age| is the age of the cache at time S. It was thus created at - // S - cache_age. - // - // Schematically: - // - // . S . N . . . . . . . T . . . . - // | | | - // set "last_refresh_" and then scheduled the next refresh; the cache - // was "cache_age" old at this point. - // | | - // some time elapsed on the test execution since then; - // this is the current time, "now" - // | - // the refresh will execute at this time - // - // So the exact delay is T - S - |cache_age|, but we don't have S here. - // - // |last_update_| was a bit before S, so if - // elapsed = now - |last_update_| then the delay is more than - // |offset_from_last_refresh| - elapsed. - // - // The delay is also less than offset_from_last_refresh, because some time - // already elapsed. Additionally, if the cache was already considered old - // when the schedule was performed then its age at that time has been - // discounted from the delay. So the delay is a bit less than - // |offset_from_last_refresh - cache_age|. - EXPECT_GE(GetLastDelay(), offset_from_last_refresh - (now - last_update_)); - EXPECT_LE(GetLastDelay(), offset_from_last_refresh - cache_age); - } - - void CheckInitialRefresh(bool with_invalidations) const { -#if defined(OS_ANDROID) - // Android takes the cache age into account for the initial fetch. - // Usually the cache age is ignored for the initial refresh, but Android - // uses it to restrain from refreshing on every startup. - base::TimeDelta rate = base::TimeDelta::FromMilliseconds( - with_invalidations - ? CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs - : kPolicyRefreshRate); - CheckTimingWithAge(rate, - base::TimeDelta::FromMinutes(kInitialCacheAgeMinutes)); -#else - // Other platforms refresh immediately. - EXPECT_EQ(base::TimeDelta(), GetLastDelay()); -#endif - } - - base::MessageLoop loop_; - MockCloudPolicyClient client_; - MockCloudPolicyStore store_; - scoped_refptr<base::TestSimpleTaskRunner> task_runner_; - scoped_ptr<net::NetworkChangeNotifier> network_change_notifier_; - - // Base time for the refresh that the scheduler should be using. - base::Time last_update_; -}; - -TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshNoPolicy) { - store_.policy_.reset(); - scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler()); - EXPECT_FALSE(task_runner_->GetPendingTasks().empty()); - EXPECT_EQ(GetLastDelay(), base::TimeDelta()); - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunUntilIdle(); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshUnmanaged) { - store_.policy_->set_state(em::PolicyData::UNMANAGED); - scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler()); - CheckTiming(CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs); - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunUntilIdle(); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshManagedNotYetFetched) { - scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler()); - EXPECT_FALSE(task_runner_->GetPendingTasks().empty()); - CheckInitialRefresh(false); - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunUntilIdle(); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshManagedAlreadyFetched) { - last_update_ = base::Time::NowFromSystemTime(); - client_.SetPolicy(PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, - std::string()), - em::PolicyFetchResponse()); - scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler()); - CheckTiming(kPolicyRefreshRate); - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunUntilIdle(); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, Unregistered) { - client_.SetDMToken(std::string()); - scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler()); - client_.NotifyPolicyFetched(); - client_.NotifyRegistrationStateChanged(); - client_.NotifyClientError(); - scheduler->SetRefreshDelay(12 * 60 * 60 * 1000); - store_.NotifyStoreLoaded(); - store_.NotifyStoreError(); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, RefreshSoonRateLimit) { - scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler()); - // Max out the request rate. - for (int i = 0; i < 5; ++i) { - EXPECT_CALL(client_, FetchPolicy()).Times(1); - scheduler->RefreshSoon(); - task_runner_->RunUntilIdle(); - Mock::VerifyAndClearExpectations(&client_); - } - // The next refresh is throttled. - EXPECT_CALL(client_, FetchPolicy()).Times(0); - scheduler->RefreshSoon(); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InvalidationsAvailable) { - scoped_ptr<CloudPolicyRefreshScheduler> scheduler( - new CloudPolicyRefreshScheduler(&client_, &store_, task_runner_)); - scheduler->SetRefreshDelay(kPolicyRefreshRate); - - // The scheduler is currently waiting for the invalidations service to - // initialize. - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - - // Signal that invalidations are available. The scheduler is currently - // waiting for any pending invalidations to be received. - scheduler->SetInvalidationServiceAvailability(true); - EXPECT_EQ(2u, task_runner_->GetPendingTasks().size()); - - // Run the invalidation service timeout task. - EXPECT_CALL(client_, FetchPolicy()).Times(0); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - - // The initial refresh is scheduled. - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - CheckInitialRefresh(true); - - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - - // Complete that fetch. - last_update_ = base::Time::NowFromSystemTime(); - client_.NotifyPolicyFetched(); - - // The next refresh has been scheduled using a lower refresh rate. - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - CheckTiming(CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InvalidationsNotAvailable) { - scoped_ptr<CloudPolicyRefreshScheduler> scheduler( - new CloudPolicyRefreshScheduler(&client_, &store_, task_runner_)); - scheduler->SetRefreshDelay(kPolicyRefreshRate); - - // The scheduler is currently waiting for the invalidations service to - // initialize. - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - - // Signal that invalidations are not available. The scheduler will keep - // waiting for us. - for (int i = 0; i < 10; ++i) { - scheduler->SetInvalidationServiceAvailability(false); - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - } - - // Run the timeout task. - EXPECT_CALL(client_, FetchPolicy()).Times(0); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - - // This scheduled the initial refresh. - CheckInitialRefresh(false); - - // Perform that fetch now. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - - // Complete that fetch. - last_update_ = base::Time::NowFromSystemTime(); - client_.NotifyPolicyFetched(); - - // The next refresh has been scheduled at the normal rate. - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - CheckTiming(kPolicyRefreshRate); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InvalidationsOffAndOn) { - scoped_ptr<CloudPolicyRefreshScheduler> scheduler( - new CloudPolicyRefreshScheduler(&client_, &store_, task_runner_)); - scheduler->SetRefreshDelay(kPolicyRefreshRate); - scheduler->SetInvalidationServiceAvailability(true); - // Initial fetch. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunUntilIdle(); - Mock::VerifyAndClearExpectations(&client_); - last_update_ = base::Time::NowFromSystemTime(); - client_.NotifyPolicyFetched(); - - // The next refresh has been scheduled using a lower refresh rate. - // Flush that task. - CheckTiming(CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs); - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - - // If the service goes down and comes back up before the timeout then a - // refresh is rescheduled at the lower rate again; after executing all - // pending tasks only 1 fetch is performed. - EXPECT_CALL(client_, FetchPolicy()).Times(0); - scheduler->SetInvalidationServiceAvailability(false); - scheduler->SetInvalidationServiceAvailability(true); - // Run the invalidation service timeout task. - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - // The next refresh has been scheduled using a lower refresh rate. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - CheckTiming(CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); -} - -TEST_F(CloudPolicyRefreshSchedulerTest, InvalidationsDisconnected) { - scoped_ptr<CloudPolicyRefreshScheduler> scheduler( - new CloudPolicyRefreshScheduler(&client_, &store_, task_runner_)); - scheduler->SetRefreshDelay(kPolicyRefreshRate); - scheduler->SetInvalidationServiceAvailability(true); - // Initial fetch. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunUntilIdle(); - Mock::VerifyAndClearExpectations(&client_); - last_update_ = base::Time::NowFromSystemTime(); - client_.NotifyPolicyFetched(); - - // The next refresh has been scheduled using a lower refresh rate. - // Flush that task. - CheckTiming(CloudPolicyRefreshScheduler::kWithInvalidationsRefreshDelayMs); - EXPECT_CALL(client_, FetchPolicy()).Times(1); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - - // If the service goes down then the refresh scheduler falls back on the - // default polling rate after a timeout. - EXPECT_CALL(client_, FetchPolicy()).Times(0); - scheduler->SetInvalidationServiceAvailability(false); - task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&client_); - // The next refresh has been scheduled at the normal rate. - CheckTiming(kPolicyRefreshRate); -} - -class CloudPolicyRefreshSchedulerSteadyStateTest - : public CloudPolicyRefreshSchedulerTest { - protected: - CloudPolicyRefreshSchedulerSteadyStateTest() {} - - virtual void SetUp() OVERRIDE { - refresh_scheduler_.reset(CreateRefreshScheduler()); - refresh_scheduler_->SetRefreshDelay(kPolicyRefreshRate); - CloudPolicyRefreshSchedulerTest::SetUp(); - last_update_ = base::Time::NowFromSystemTime(); - client_.NotifyPolicyFetched(); - CheckTiming(kPolicyRefreshRate); - } - - scoped_ptr<CloudPolicyRefreshScheduler> refresh_scheduler_; -}; - -TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnPolicyFetched) { - client_.NotifyPolicyFetched(); - CheckTiming(kPolicyRefreshRate); -} - -TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnRegistrationStateChanged) { - client_.SetDMToken("new_token"); - client_.NotifyRegistrationStateChanged(); - EXPECT_EQ(GetLastDelay(), base::TimeDelta()); - - task_runner_->ClearPendingTasks(); - client_.SetDMToken(std::string()); - client_.NotifyRegistrationStateChanged(); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); -} - -TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnStoreLoaded) { - store_.NotifyStoreLoaded(); - CheckTiming(kPolicyRefreshRate); -} - -TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnStoreError) { - task_runner_->ClearPendingTasks(); - store_.NotifyStoreError(); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); -} - -TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, RefreshDelayChange) { - const int delay_short_ms = 5 * 60 * 1000; - refresh_scheduler_->SetRefreshDelay(delay_short_ms); - CheckTiming(CloudPolicyRefreshScheduler::kRefreshDelayMinMs); - - const int delay_ms = 12 * 60 * 60 * 1000; - refresh_scheduler_->SetRefreshDelay(delay_ms); - CheckTiming(delay_ms); - - const int delay_long_ms = 20 * 24 * 60 * 60 * 1000; - refresh_scheduler_->SetRefreshDelay(delay_long_ms); - CheckTiming(CloudPolicyRefreshScheduler::kRefreshDelayMaxMs); -} - -TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnIPAddressChanged) { - NotifyIPAddressChanged(); - CheckTiming(kPolicyRefreshRate); - - client_.SetStatus(DM_STATUS_REQUEST_FAILED); - NotifyIPAddressChanged(); - EXPECT_EQ(GetLastDelay(), base::TimeDelta()); -} - -struct ClientErrorTestParam { - DeviceManagementStatus client_error; - int64 expected_delay_ms; - int backoff_factor; -}; - -static const ClientErrorTestParam kClientErrorTestCases[] = { - { DM_STATUS_REQUEST_INVALID, - CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs, 1 }, - { DM_STATUS_REQUEST_FAILED, - CloudPolicyRefreshScheduler::kInitialErrorRetryDelayMs, 2 }, - { DM_STATUS_TEMPORARY_UNAVAILABLE, - CloudPolicyRefreshScheduler::kInitialErrorRetryDelayMs, 2 }, - { DM_STATUS_HTTP_STATUS_ERROR, - CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs, 1 }, - { DM_STATUS_RESPONSE_DECODING_ERROR, - CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs, 1 }, - { DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED, - CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs, 1 }, - { DM_STATUS_SERVICE_DEVICE_NOT_FOUND, - -1, 1 }, - { DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID, - -1, 1 }, - { DM_STATUS_SERVICE_ACTIVATION_PENDING, - kPolicyRefreshRate, 1 }, - { DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER, - -1, 1 }, - { DM_STATUS_SERVICE_MISSING_LICENSES, - -1, 1 }, - { DM_STATUS_SERVICE_DEVICE_ID_CONFLICT, - -1, 1 }, - { DM_STATUS_SERVICE_POLICY_NOT_FOUND, - kPolicyRefreshRate, 1 }, -}; - -class CloudPolicyRefreshSchedulerClientErrorTest - : public CloudPolicyRefreshSchedulerSteadyStateTest, - public testing::WithParamInterface<ClientErrorTestParam> { -}; - -TEST_P(CloudPolicyRefreshSchedulerClientErrorTest, OnClientError) { - client_.SetStatus(GetParam().client_error); - task_runner_->ClearPendingTasks(); - - // See whether the error triggers the right refresh delay. - int64 expected_delay_ms = GetParam().expected_delay_ms; - client_.NotifyClientError(); - if (expected_delay_ms >= 0) { - CheckTiming(expected_delay_ms); - - // Check whether exponential backoff is working as expected and capped at - // the regular refresh rate (if applicable). - do { - expected_delay_ms *= GetParam().backoff_factor; - last_update_ = base::Time::NowFromSystemTime(); - client_.NotifyClientError(); - CheckTiming(std::max(std::min(expected_delay_ms, kPolicyRefreshRate), - GetParam().expected_delay_ms)); - } while (GetParam().backoff_factor > 1 && - expected_delay_ms <= kPolicyRefreshRate); - } else { - EXPECT_EQ(base::TimeDelta(), GetLastDelay()); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); - } -} - -INSTANTIATE_TEST_CASE_P(CloudPolicyRefreshSchedulerClientErrorTest, - CloudPolicyRefreshSchedulerClientErrorTest, - testing::ValuesIn(kClientErrorTestCases)); - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_service.cc b/chrome/browser/policy/cloud/cloud_policy_service.cc deleted file mode 100644 index fd71677..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_service.cc +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_service.h" - -#include "base/callback.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" - -namespace em = enterprise_management; - -namespace policy { - -CloudPolicyService::CloudPolicyService(const PolicyNamespaceKey& policy_ns_key, - CloudPolicyClient* client, - CloudPolicyStore* store) - : policy_ns_key_(policy_ns_key), - client_(client), - store_(store), - refresh_state_(REFRESH_NONE), - initialization_complete_(false) { - client_->AddNamespaceToFetch(policy_ns_key_); - client_->AddObserver(this); - store_->AddObserver(this); - - // Make sure we initialize |client_| from the policy data that might be - // already present in |store_|. - OnStoreLoaded(store_); -} - -CloudPolicyService::~CloudPolicyService() { - client_->RemoveNamespaceToFetch(policy_ns_key_); - client_->RemoveObserver(this); - store_->RemoveObserver(this); -} - -std::string CloudPolicyService::ManagedBy() const { - const em::PolicyData* policy = store_->policy(); - if (policy) { - std::string username = policy->username(); - std::size_t pos = username.find('@'); - if (pos != std::string::npos) - return username.substr(pos + 1); - } - return std::string(); -} - -void CloudPolicyService::RefreshPolicy(const RefreshPolicyCallback& callback) { - // If the client is not registered, bail out. - if (!client_->is_registered()) { - callback.Run(false); - return; - } - - // Else, trigger a refresh. - refresh_callbacks_.push_back(callback); - refresh_state_ = REFRESH_POLICY_FETCH; - client_->FetchPolicy(); -} - -void CloudPolicyService::OnPolicyFetched(CloudPolicyClient* client) { - if (client_->status() != DM_STATUS_SUCCESS) { - RefreshCompleted(false); - return; - } - - const em::PolicyFetchResponse* policy = client_->GetPolicyFor(policy_ns_key_); - if (policy) { - if (refresh_state_ != REFRESH_NONE) - refresh_state_ = REFRESH_POLICY_STORE; - store_->Store(*policy, client->fetched_invalidation_version()); - } else { - RefreshCompleted(false); - } -} - -void CloudPolicyService::OnRegistrationStateChanged(CloudPolicyClient* client) { -} - -void CloudPolicyService::OnClientError(CloudPolicyClient* client) { - if (refresh_state_ == REFRESH_POLICY_FETCH) - RefreshCompleted(false); -} - -void CloudPolicyService::OnStoreLoaded(CloudPolicyStore* store) { - // Update the client with state from the store. - const em::PolicyData* policy(store_->policy()); - - // Timestamp. - base::Time policy_timestamp; - if (policy && policy->has_timestamp()) { - policy_timestamp = - base::Time::UnixEpoch() + - base::TimeDelta::FromMilliseconds(policy->timestamp()); - } - client_->set_last_policy_timestamp(policy_timestamp); - - // Public key version. - if (policy && policy->has_public_key_version()) - client_->set_public_key_version(policy->public_key_version()); - else - client_->clear_public_key_version(); - - // Whether to submit the machine ID. - bool submit_machine_id = false; - if (policy && policy->has_valid_serial_number_missing()) - submit_machine_id = policy->valid_serial_number_missing(); - client_->set_submit_machine_id(submit_machine_id); - - // Finally, set up registration if necessary. - if (policy && policy->has_request_token() && policy->has_device_id() && - !client_->is_registered()) { - DVLOG(1) << "Setting up registration with request token: " - << policy->request_token(); - client_->SetupRegistration(policy->request_token(), - policy->device_id()); - } - - if (refresh_state_ == REFRESH_POLICY_STORE) - RefreshCompleted(true); - - CheckInitializationCompleted(); -} - -void CloudPolicyService::OnStoreError(CloudPolicyStore* store) { - if (refresh_state_ == REFRESH_POLICY_STORE) - RefreshCompleted(false); - CheckInitializationCompleted(); -} - -void CloudPolicyService::CheckInitializationCompleted() { - if (!IsInitializationComplete() && store_->is_initialized()) { - initialization_complete_ = true; - FOR_EACH_OBSERVER(Observer, observers_, OnInitializationCompleted(this)); - } -} - -void CloudPolicyService::RefreshCompleted(bool success) { - // Clear state and |refresh_callbacks_| before actually invoking them, s.t. - // triggering new policy fetches behaves as expected. - std::vector<RefreshPolicyCallback> callbacks; - callbacks.swap(refresh_callbacks_); - refresh_state_ = REFRESH_NONE; - - for (std::vector<RefreshPolicyCallback>::iterator callback(callbacks.begin()); - callback != callbacks.end(); - ++callback) { - callback->Run(success); - } -} - -void CloudPolicyService::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void CloudPolicyService::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_service.h b/chrome/browser/policy/cloud/cloud_policy_service.h deleted file mode 100644 index 9437527..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_service.h +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_SERVICE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_SERVICE_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/compiler_specific.h" -#include "base/observer_list.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" - -namespace policy { - -// Coordinates cloud policy handling, moving downloaded policy from the client -// to the store, and setting up client registrations from cached data in the -// store. Also coordinates actions on policy refresh triggers. -class CloudPolicyService : public CloudPolicyClient::Observer, - public CloudPolicyStore::Observer { - public: - // Callback invoked once the policy refresh attempt has completed. Passed - // bool parameter is true if the refresh was successful (no error). - typedef base::Callback<void(bool)> RefreshPolicyCallback; - - class Observer { - public: - // Invoked when CloudPolicyService has finished initializing (any initial - // policy load activity has completed and the CloudPolicyClient has - // been registered, if possible). - virtual void OnInitializationCompleted(CloudPolicyService* service) = 0; - virtual ~Observer() {} - }; - - // |client| and |store| must remain valid for the object life time. - CloudPolicyService(const PolicyNamespaceKey& policy_ns_key, - CloudPolicyClient* client, - CloudPolicyStore* store); - virtual ~CloudPolicyService(); - - // Returns the domain that manages this user/device, according to the current - // policy blob. Empty if not managed/not available. - std::string ManagedBy() const; - - // Refreshes policy. |callback| will be invoked after the operation completes - // or aborts because of errors. - void RefreshPolicy(const RefreshPolicyCallback& callback); - - // Adds/Removes an Observer for this object. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - // CloudPolicyClient::Observer: - virtual void OnPolicyFetched(CloudPolicyClient* client) OVERRIDE; - virtual void OnRegistrationStateChanged(CloudPolicyClient* client) OVERRIDE; - virtual void OnClientError(CloudPolicyClient* client) OVERRIDE; - - // CloudPolicyStore::Observer: - virtual void OnStoreLoaded(CloudPolicyStore* store) OVERRIDE; - virtual void OnStoreError(CloudPolicyStore* store) OVERRIDE; - - bool IsInitializationComplete() const { return initialization_complete_; } - - private: - // Helper function that is called when initialization may be complete, and - // which is responsible for notifying observers. - void CheckInitializationCompleted(); - - // Invokes the refresh callbacks and clears refresh state. The |success| flag - // is passed through to the refresh callbacks. - void RefreshCompleted(bool success); - - // The policy namespace fetched by |client_| and expected by |store_|. - PolicyNamespaceKey policy_ns_key_; - - // The client used to talk to the cloud. - CloudPolicyClient* client_; - - // Takes care of persisting and decoding cloud policy. - CloudPolicyStore* store_; - - // Tracks the state of a pending refresh operation, if any. - enum { - // No refresh pending. - REFRESH_NONE, - // Policy fetch is pending. - REFRESH_POLICY_FETCH, - // Policy store is pending. - REFRESH_POLICY_STORE, - } refresh_state_; - - // Callbacks to invoke upon policy refresh. - std::vector<RefreshPolicyCallback> refresh_callbacks_; - - // Set to true once the service is initialized (initial policy load/refresh - // is complete). - bool initialization_complete_; - - // Observers who will receive notifications when the service has finished - // initializing. - ObserverList<Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyService); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_SERVICE_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_service_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_service_unittest.cc deleted file mode 100644 index 68c22ee..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_service_unittest.cc +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_service.h" - -#include "base/bind.h" -#include "base/callback.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace em = enterprise_management; - -using testing::_; - -namespace policy { - -class MockCloudPolicyServiceObserver : public CloudPolicyService::Observer { - public: - MockCloudPolicyServiceObserver() {} - virtual ~MockCloudPolicyServiceObserver() {} - - MOCK_METHOD1(OnInitializationCompleted, void(CloudPolicyService* service)); - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudPolicyServiceObserver); -}; - -class CloudPolicyServiceTest : public testing::Test { - public: - CloudPolicyServiceTest() - : policy_ns_key_(dm_protocol::kChromeUserPolicyType, std::string()), - service_(policy_ns_key_, &client_, &store_) {} - - MOCK_METHOD1(OnPolicyRefresh, void(bool)); - - protected: - PolicyNamespaceKey policy_ns_key_; - MockCloudPolicyClient client_; - MockCloudPolicyStore store_; - CloudPolicyService service_; -}; - -MATCHER_P(ProtoMatches, proto, "") { - return arg.SerializePartialAsString() == proto.SerializePartialAsString(); -} - -TEST_F(CloudPolicyServiceTest, ManagedByEmptyPolicy) { - EXPECT_EQ("", service_.ManagedBy()); -} - -TEST_F(CloudPolicyServiceTest, ManagedByValidPolicy) { - store_.policy_.reset(new em::PolicyData()); - store_.policy_->set_username("user@example.com"); - EXPECT_EQ("example.com", service_.ManagedBy()); -} - -TEST_F(CloudPolicyServiceTest, PolicyUpdateSuccess) { - em::PolicyFetchResponse policy; - policy.set_policy_data("fake policy"); - client_.SetPolicy(policy_ns_key_, policy); - EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1); - client_.NotifyPolicyFetched(); - - // After |store_| initializes, credentials and other meta data should be - // transferred to |client_|. - store_.policy_.reset(new em::PolicyData()); - store_.policy_->set_request_token("fake token"); - store_.policy_->set_device_id("fake client id"); - store_.policy_->set_timestamp(32); - store_.policy_->set_valid_serial_number_missing(true); - store_.policy_->set_public_key_version(17); - EXPECT_CALL(client_, - SetupRegistration(store_.policy_->request_token(), - store_.policy_->device_id())).Times(1); - store_.NotifyStoreLoaded(); - EXPECT_EQ(base::Time::UnixEpoch() + base::TimeDelta::FromMilliseconds(32), - client_.last_policy_timestamp_); - EXPECT_TRUE(client_.submit_machine_id_); - EXPECT_TRUE(client_.public_key_version_valid_); - EXPECT_EQ(17, client_.public_key_version_); -} - -TEST_F(CloudPolicyServiceTest, PolicyUpdateClientFailure) { - client_.SetStatus(DM_STATUS_REQUEST_FAILED); - EXPECT_CALL(store_, Store(_)).Times(0); - client_.NotifyPolicyFetched(); -} - -TEST_F(CloudPolicyServiceTest, RefreshPolicySuccess) { - testing::InSequence seq; - - EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0); - client_.SetDMToken("fake token"); - - // Trigger a fetch on the client. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - - // Client responds, push policy to store. - em::PolicyFetchResponse policy; - policy.set_policy_data("fake policy"); - client_.SetPolicy(policy_ns_key_, policy); - client_.fetched_invalidation_version_ = 12345; - EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1); - EXPECT_EQ(0, store_.invalidation_version()); - client_.NotifyPolicyFetched(); - EXPECT_EQ(12345, store_.invalidation_version()); - - // Store reloads policy, callback gets triggered. - store_.policy_.reset(new em::PolicyData()); - store_.policy_->set_request_token("token"); - store_.policy_->set_device_id("device-id"); - EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1); - store_.NotifyStoreLoaded(); -} - -TEST_F(CloudPolicyServiceTest, RefreshPolicyNotRegistered) { - // Clear the token so the client is not registered. - client_.SetDMToken(std::string()); - - EXPECT_CALL(client_, FetchPolicy()).Times(0); - EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); -} - -TEST_F(CloudPolicyServiceTest, RefreshPolicyClientError) { - testing::InSequence seq; - - EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0); - client_.SetDMToken("fake token"); - - // Trigger a fetch on the client. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - - // Client responds with an error, which should trigger the callback. - client_.SetStatus(DM_STATUS_REQUEST_FAILED); - EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1); - client_.NotifyClientError(); -} - -TEST_F(CloudPolicyServiceTest, RefreshPolicyStoreError) { - testing::InSequence seq; - - EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0); - client_.SetDMToken("fake token"); - - // Trigger a fetch on the client. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - - // Client responds, push policy to store. - em::PolicyFetchResponse policy; - policy.set_policy_data("fake policy"); - client_.SetPolicy(policy_ns_key_, policy); - EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1); - client_.NotifyPolicyFetched(); - - // Store fails, which should trigger the callback. - EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1); - store_.NotifyStoreError(); -} - -TEST_F(CloudPolicyServiceTest, RefreshPolicyConcurrent) { - testing::InSequence seq; - - EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0); - client_.SetDMToken("fake token"); - - // Trigger a fetch on the client. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - - // Triggering another policy refresh should generate a new fetch request. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - - // Client responds, push policy to store. - em::PolicyFetchResponse policy; - policy.set_policy_data("fake policy"); - client_.SetPolicy(policy_ns_key_, policy); - EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1); - client_.NotifyPolicyFetched(); - - // Trigger another policy fetch. - EXPECT_CALL(client_, FetchPolicy()).Times(1); - service_.RefreshPolicy(base::Bind(&CloudPolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - - // The store finishing the first load should not generate callbacks. - EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0); - store_.NotifyStoreLoaded(); - - // Second policy fetch finishes. - EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1); - client_.NotifyPolicyFetched(); - - // Corresponding store operation finishes, all _three_ callbacks fire. - EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(3); - store_.NotifyStoreLoaded(); -} - -TEST_F(CloudPolicyServiceTest, StoreAlreadyInitialized) { - // Service should start off initialized if the store has already loaded - // policy. - store_.NotifyStoreLoaded(); - CloudPolicyService service(policy_ns_key_, &client_, &store_); - EXPECT_TRUE(service.IsInitializationComplete()); -} - -TEST_F(CloudPolicyServiceTest, StoreLoadAfterCreation) { - // Service should start off un-initialized if the store has not yet loaded - // policy. - EXPECT_FALSE(service_.IsInitializationComplete()); - MockCloudPolicyServiceObserver observer; - service_.AddObserver(&observer); - // Service should be marked as initialized and observer should be called back. - EXPECT_CALL(observer, OnInitializationCompleted(&service_)).Times(1); - store_.NotifyStoreLoaded(); - EXPECT_TRUE(service_.IsInitializationComplete()); - testing::Mock::VerifyAndClearExpectations(&observer); - - // Now, the next time the store is loaded, the observer should not be called - // again. - EXPECT_CALL(observer, OnInitializationCompleted(&service_)).Times(0); - store_.NotifyStoreLoaded(); - service_.RemoveObserver(&observer); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_store.cc b/chrome/browser/policy/cloud/cloud_policy_store.cc deleted file mode 100644 index 2c6dca7..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_store.cc +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_store.h" - -#include "base/logging.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" - -namespace policy { - -CloudPolicyStore::Observer::~Observer() {} - -CloudPolicyStore::CloudPolicyStore() - : status_(STATUS_OK), - validation_status_(CloudPolicyValidatorBase::VALIDATION_OK), - invalidation_version_(0), - is_initialized_(false) {} - -CloudPolicyStore::~CloudPolicyStore() { - DCHECK(!external_data_manager_); -} - -void CloudPolicyStore::Store( - const enterprise_management::PolicyFetchResponse& policy, - int64 invalidation_version) { - invalidation_version_ = invalidation_version; - Store(policy); -} - -void CloudPolicyStore::AddObserver(CloudPolicyStore::Observer* observer) { - observers_.AddObserver(observer); -} - -void CloudPolicyStore::RemoveObserver(CloudPolicyStore::Observer* observer) { - observers_.RemoveObserver(observer); -} - -void CloudPolicyStore::NotifyStoreLoaded() { - is_initialized_ = true; - // The |external_data_manager_| must be notified first so that when other - // observers are informed about the changed policies and try to fetch external - // data referenced by these, the |external_data_manager_| has the required - // metadata already. - if (external_data_manager_) - external_data_manager_->OnPolicyStoreLoaded(); - FOR_EACH_OBSERVER(Observer, observers_, OnStoreLoaded(this)); -} - -void CloudPolicyStore::NotifyStoreError() { - is_initialized_ = true; - FOR_EACH_OBSERVER(Observer, observers_, OnStoreError(this)); -} - -void CloudPolicyStore::SetExternalDataManager( - base::WeakPtr<CloudExternalDataManager> external_data_manager) { - DCHECK(!external_data_manager_); - external_data_manager_ = external_data_manager; - if (is_initialized_) - external_data_manager_->OnPolicyStoreLoaded(); -} - -void CloudPolicyStore::SetPolicyMapForTesting(const PolicyMap& policy_map) { - policy_map_.CopyFrom(policy_map); - NotifyStoreLoaded(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_store.h b/chrome/browser/policy/cloud/cloud_policy_store.h deleted file mode 100644 index 2f26e6e..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_store.h +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_STORE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_STORE_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "components/policy/core/common/policy_map.h" - -namespace policy { - -class CloudExternalDataManager; - -// Defines the low-level interface used by the cloud policy code to: -// 1. Validate policy blobs that should be applied locally -// 2. Persist policy blobs -// 3. Decode policy blobs to PolicyMap representation -class CloudPolicyStore { - public: - // Status codes. - enum Status { - // Everything is in good order. - STATUS_OK, - // Loading policy from the underlying data store failed. - STATUS_LOAD_ERROR, - // Failed to store policy to the data store. - STATUS_STORE_ERROR, - // Failed to parse the policy read from the data store. - STATUS_PARSE_ERROR, - // Failed to serialize policy for storage. - STATUS_SERIALIZE_ERROR, - // Validation error. - STATUS_VALIDATION_ERROR, - // Store cannot accept policy (e.g. non-enterprise device). - STATUS_BAD_STATE, - }; - - // Callbacks for policy store events. Most importantly, policy updates. - class Observer { - public: - virtual ~Observer(); - - // Called on changes to store->policy() and/or store->policy_map(). - virtual void OnStoreLoaded(CloudPolicyStore* store) = 0; - - // Called upon encountering errors. - virtual void OnStoreError(CloudPolicyStore* store) = 0; - }; - - CloudPolicyStore(); - virtual ~CloudPolicyStore(); - - // Indicates whether the store has been fully initialized. This is - // accomplished by calling Load() after startup. - bool is_initialized() const { return is_initialized_; } - - base::WeakPtr<CloudExternalDataManager> external_data_manager() const { - return external_data_manager_; - } - - const PolicyMap& policy_map() const { return policy_map_; } - bool has_policy() const { - return policy_.get() != NULL; - } - const enterprise_management::PolicyData* policy() const { - return policy_.get(); - } - bool is_managed() const { - return policy_.get() && - policy_->state() == enterprise_management::PolicyData::ACTIVE; - } - Status status() const { return status_; } - CloudPolicyValidatorBase::Status validation_status() const { - return validation_status_; - } - - // Store a new policy blob. Pending load/store operations will be canceled. - // The store operation may proceed asynchronously and observers are notified - // once the operation finishes. If successful, OnStoreLoaded() will be invoked - // on the observers and the updated policy can be read through policy(). - // Errors generate OnStoreError() notifications. - // |invalidation_version| is the invalidation version of the policy to be - // stored. - void Store( - const enterprise_management::PolicyFetchResponse& policy, - int64 invalidation_version); - - virtual void Store( - const enterprise_management::PolicyFetchResponse& policy) = 0; - - // Load the current policy blob from persistent storage. Pending load/store - // operations will be canceled. This may trigger asynchronous operations. - // Upon success, OnStoreLoaded() will be called on the registered observers. - // Otherwise, OnStoreError() reports the reason for failure. - virtual void Load() = 0; - - // Registers an observer to be notified when policy changes. - void AddObserver(Observer* observer); - - // Removes the specified observer. - void RemoveObserver(Observer* observer); - - // The invalidation version of the last policy stored. This value can be read - // by observers to determine which version of the policy is now available. - int64 invalidation_version() { - return invalidation_version_; - } - - // Indicate that external data referenced by policies in this store is managed - // by |external_data_manager|. The |external_data_manager| will be notified - // about policy changes before any other observers. - void SetExternalDataManager( - base::WeakPtr<CloudExternalDataManager> external_data_manager); - - // Replaces |policy_map_| and calls the registered observers, simulating a - // successful load of |policy_map| from persistent storage. - // TODO(bartfab): This override is only needed because there are no policies - // that reference external data and therefore, no ExternalDataFetchers in the - // |policy_map_|. Once the first such policy is added, use that policy in - // tests and remove the override. - void SetPolicyMapForTesting(const PolicyMap& policy_map); - - protected: - // Invokes the corresponding callback on all registered observers. - void NotifyStoreLoaded(); - void NotifyStoreError(); - - // Manages external data referenced by policies. - base::WeakPtr<CloudExternalDataManager> external_data_manager_; - - // Decoded version of the currently effective policy. - PolicyMap policy_map_; - - // Currently effective policy. - scoped_ptr<enterprise_management::PolicyData> policy_; - - // Latest status code. - Status status_; - - // Latest validation status. - CloudPolicyValidatorBase::Status validation_status_; - - // The invalidation version of the last policy stored. - int64 invalidation_version_; - - private: - // Whether the store has completed asynchronous initialization, which is - // triggered by calling Load(). - bool is_initialized_; - - ObserverList<Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyStore); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_STORE_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_validator.cc b/chrome/browser/policy/cloud/cloud_policy_validator.cc deleted file mode 100644 index 8e148e2..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_validator.cc +++ /dev/null @@ -1,382 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" - -#include "base/bind_helpers.h" -#include "base/message_loop/message_loop.h" -#include "base/sequenced_task_runner.h" -#include "base/stl_util.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "crypto/signature_verifier.h" -#include "google_apis/gaia/gaia_auth_util.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -// Grace interval for policy timestamp checks, in seconds. -const int kTimestampGraceIntervalSeconds = 60; - -// DER-encoded ASN.1 object identifier for the SHA1-RSA signature algorithm. -const uint8 kSignatureAlgorithm[] = { - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, - 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00 -}; - -} // namespace - -CloudPolicyValidatorBase::~CloudPolicyValidatorBase() {} - -void CloudPolicyValidatorBase::ValidateTimestamp( - base::Time not_before, - base::Time now, - ValidateTimestampOption timestamp_option) { - // Timestamp should be from the past. We allow for a 1-minute grace interval - // to cover clock drift. - validation_flags_ |= VALIDATE_TIMESTAMP; - timestamp_not_before_ = - (not_before - base::Time::UnixEpoch()).InMilliseconds(); - timestamp_not_after_ = - ((now + base::TimeDelta::FromSeconds(kTimestampGraceIntervalSeconds)) - - base::Time::UnixEpoch()).InMillisecondsRoundedUp(); - timestamp_option_ = timestamp_option; -} - -void CloudPolicyValidatorBase::ValidateUsername( - const std::string& expected_user) { - validation_flags_ |= VALIDATE_USERNAME; - user_ = gaia::CanonicalizeEmail(expected_user); -} - -void CloudPolicyValidatorBase::ValidateDomain( - const std::string& expected_domain) { - validation_flags_ |= VALIDATE_DOMAIN; - domain_ = gaia::CanonicalizeDomain(expected_domain); -} - -void CloudPolicyValidatorBase::ValidateDMToken( - const std::string& token, - ValidateDMTokenOption dm_token_option) { - validation_flags_ |= VALIDATE_TOKEN; - token_ = token; - dm_token_option_ = dm_token_option; -} - -void CloudPolicyValidatorBase::ValidatePolicyType( - const std::string& policy_type) { - validation_flags_ |= VALIDATE_POLICY_TYPE; - policy_type_ = policy_type; -} - -void CloudPolicyValidatorBase::ValidateSettingsEntityId( - const std::string& settings_entity_id) { - validation_flags_ |= VALIDATE_ENTITY_ID; - settings_entity_id_ = settings_entity_id; -} - -void CloudPolicyValidatorBase::ValidatePayload() { - validation_flags_ |= VALIDATE_PAYLOAD; -} - -void CloudPolicyValidatorBase::ValidateSignature(const std::vector<uint8>& key, - bool allow_key_rotation) { - validation_flags_ |= VALIDATE_SIGNATURE; - key_ = std::string(reinterpret_cast<const char*>(vector_as_array(&key)), - key.size()); - allow_key_rotation_ = allow_key_rotation; -} - -void CloudPolicyValidatorBase::ValidateInitialKey() { - validation_flags_ |= VALIDATE_INITIAL_KEY; -} - -void CloudPolicyValidatorBase::ValidateAgainstCurrentPolicy( - const em::PolicyData* policy_data, - ValidateTimestampOption timestamp_option, - ValidateDMTokenOption dm_token_option) { - base::Time last_policy_timestamp; - std::string expected_dm_token; - if (policy_data) { - last_policy_timestamp = - base::Time::UnixEpoch() + - base::TimeDelta::FromMilliseconds(policy_data->timestamp()); - expected_dm_token = policy_data->request_token(); - } - ValidateTimestamp(last_policy_timestamp, base::Time::NowFromSystemTime(), - timestamp_option); - ValidateDMToken(expected_dm_token, dm_token_option); -} - -CloudPolicyValidatorBase::CloudPolicyValidatorBase( - scoped_ptr<em::PolicyFetchResponse> policy_response, - google::protobuf::MessageLite* payload, - scoped_refptr<base::SequencedTaskRunner> background_task_runner) - : status_(VALIDATION_OK), - policy_(policy_response.Pass()), - payload_(payload), - validation_flags_(0), - timestamp_not_before_(0), - timestamp_not_after_(0), - timestamp_option_(TIMESTAMP_REQUIRED), - dm_token_option_(DM_TOKEN_REQUIRED), - allow_key_rotation_(false), - background_task_runner_(background_task_runner) {} - -void CloudPolicyValidatorBase::PostValidationTask( - const base::Closure& completion_callback) { - background_task_runner_->PostTask( - FROM_HERE, - base::Bind(&CloudPolicyValidatorBase::PerformValidation, - base::Passed(scoped_ptr<CloudPolicyValidatorBase>(this)), - base::MessageLoop::current()->message_loop_proxy(), - completion_callback)); -} - -// static -void CloudPolicyValidatorBase::PerformValidation( - scoped_ptr<CloudPolicyValidatorBase> self, - scoped_refptr<base::MessageLoopProxy> message_loop, - const base::Closure& completion_callback) { - // Run the validation activities on this thread. - self->RunValidation(); - - // Report completion on |message_loop|. - message_loop->PostTask( - FROM_HERE, - base::Bind(&CloudPolicyValidatorBase::ReportCompletion, - base::Passed(&self), - completion_callback)); -} - -// static -void CloudPolicyValidatorBase::ReportCompletion( - scoped_ptr<CloudPolicyValidatorBase> self, - const base::Closure& completion_callback) { - completion_callback.Run(); -} - -void CloudPolicyValidatorBase::RunValidation() { - policy_data_.reset(new em::PolicyData()); - RunChecks(); -} - -void CloudPolicyValidatorBase::RunChecks() { - status_ = VALIDATION_OK; - if ((policy_->has_error_code() && policy_->error_code() != 200) || - (policy_->has_error_message() && !policy_->error_message().empty())) { - LOG(ERROR) << "Error in policy blob." - << " code: " << policy_->error_code() - << " message: " << policy_->error_message(); - status_ = VALIDATION_ERROR_CODE_PRESENT; - return; - } - - // Parse policy data. - if (!policy_data_->ParseFromString(policy_->policy_data()) || - !policy_data_->IsInitialized()) { - LOG(ERROR) << "Failed to parse policy response"; - status_ = VALIDATION_PAYLOAD_PARSE_ERROR; - return; - } - - // Table of checks we run. These are sorted by descending severity of the - // error, s.t. the most severe check will determine the validation status. - static const struct { - int flag; - Status (CloudPolicyValidatorBase::* checkFunction)(); - } kCheckFunctions[] = { - { VALIDATE_SIGNATURE, &CloudPolicyValidatorBase::CheckSignature }, - { VALIDATE_INITIAL_KEY, &CloudPolicyValidatorBase::CheckInitialKey }, - { VALIDATE_POLICY_TYPE, &CloudPolicyValidatorBase::CheckPolicyType }, - { VALIDATE_ENTITY_ID, &CloudPolicyValidatorBase::CheckEntityId }, - { VALIDATE_TOKEN, &CloudPolicyValidatorBase::CheckToken }, - { VALIDATE_USERNAME, &CloudPolicyValidatorBase::CheckUsername }, - { VALIDATE_DOMAIN, &CloudPolicyValidatorBase::CheckDomain }, - { VALIDATE_TIMESTAMP, &CloudPolicyValidatorBase::CheckTimestamp }, - { VALIDATE_PAYLOAD, &CloudPolicyValidatorBase::CheckPayload }, - }; - - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kCheckFunctions); ++i) { - if (validation_flags_ & kCheckFunctions[i].flag) { - status_ = (this->*(kCheckFunctions[i].checkFunction))(); - if (status_ != VALIDATION_OK) - break; - } - } -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckSignature() { - const std::string* signature_key = &key_; - if (policy_->has_new_public_key() && allow_key_rotation_) { - signature_key = &policy_->new_public_key(); - if (!policy_->has_new_public_key_signature() || - !VerifySignature(policy_->new_public_key(), key_, - policy_->new_public_key_signature())) { - LOG(ERROR) << "New public key signature verification failed"; - return VALIDATION_BAD_SIGNATURE; - } - } - - if (!policy_->has_policy_data_signature() || - !VerifySignature(policy_->policy_data(), *signature_key, - policy_->policy_data_signature())) { - LOG(ERROR) << "Policy signature validation failed"; - return VALIDATION_BAD_SIGNATURE; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckInitialKey() { - if (!policy_->has_new_public_key() || - !policy_->has_policy_data_signature() || - !VerifySignature(policy_->policy_data(), policy_->new_public_key(), - policy_->policy_data_signature())) { - LOG(ERROR) << "Initial policy signature validation failed"; - return VALIDATION_BAD_INITIAL_SIGNATURE; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckPolicyType() { - if (!policy_data_->has_policy_type() || - policy_data_->policy_type() != policy_type_) { - LOG(ERROR) << "Wrong policy type " << policy_data_->policy_type(); - return VALIDATION_WRONG_POLICY_TYPE; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckEntityId() { - if (!policy_data_->has_settings_entity_id() || - policy_data_->settings_entity_id() != settings_entity_id_) { - LOG(ERROR) << "Wrong settings_entity_id " - << policy_data_->settings_entity_id() << ", expected " - << settings_entity_id_; - return VALIDATION_WRONG_SETTINGS_ENTITY_ID; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckTimestamp() { - if (!policy_data_->has_timestamp()) { - if (timestamp_option_ == TIMESTAMP_NOT_REQUIRED) { - return VALIDATION_OK; - } else { - LOG(ERROR) << "Policy timestamp missing"; - return VALIDATION_BAD_TIMESTAMP; - } - } - - if (timestamp_option_ != TIMESTAMP_NOT_REQUIRED && - policy_data_->timestamp() < timestamp_not_before_) { - // If |timestamp_option_| is TIMESTAMP_REQUIRED or TIMESTAMP_NOT_BEFORE - // then this is a failure. - LOG(ERROR) << "Policy too old: " << policy_data_->timestamp(); - return VALIDATION_BAD_TIMESTAMP; - } - if (timestamp_option_ == TIMESTAMP_REQUIRED && - policy_data_->timestamp() > timestamp_not_after_) { - LOG(ERROR) << "Policy from the future: " << policy_data_->timestamp(); - return VALIDATION_BAD_TIMESTAMP; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckToken() { - // Make sure the token matches the expected token (if any) and also - // make sure the token itself is valid (non-empty if DM_TOKEN_REQUIRED). - if (dm_token_option_ == DM_TOKEN_REQUIRED && - (!policy_data_->has_request_token() || - policy_data_->request_token().empty())) { - LOG(ERROR) << "Empty DM token encountered - expected: " << token_; - return VALIDATION_WRONG_TOKEN; - } - if (!token_.empty() && policy_data_->request_token() != token_) { - LOG(ERROR) << "Invalid DM token: " << policy_data_->request_token() - << " - expected: " << token_; - return VALIDATION_WRONG_TOKEN; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckUsername() { - if (!policy_data_->has_username()) { - LOG(ERROR) << "Policy is missing user name"; - return VALIDATION_BAD_USERNAME; - } - - std::string policy_username = - gaia::CanonicalizeEmail(gaia::SanitizeEmail(policy_data_->username())); - - if (user_ != policy_username) { - LOG(ERROR) << "Invalid user name " << policy_data_->username(); - return VALIDATION_BAD_USERNAME; - } - - return VALIDATION_OK; -} - - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDomain() { - if (!policy_data_->has_username()) { - LOG(ERROR) << "Policy is missing user name"; - return VALIDATION_BAD_USERNAME; - } - - std::string policy_domain = - gaia::ExtractDomainName( - gaia::CanonicalizeEmail( - gaia::SanitizeEmail(policy_data_->username()))); - - if (domain_ != policy_domain) { - LOG(ERROR) << "Invalid user name " << policy_data_->username(); - return VALIDATION_BAD_USERNAME; - } - - return VALIDATION_OK; -} - -CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckPayload() { - if (!policy_data_->has_policy_value() || - !payload_->ParseFromString(policy_data_->policy_value()) || - !payload_->IsInitialized()) { - LOG(ERROR) << "Failed to decode policy payload protobuf"; - return VALIDATION_POLICY_PARSE_ERROR; - } - - return VALIDATION_OK; -} - -// static -bool CloudPolicyValidatorBase::VerifySignature(const std::string& data, - const std::string& key, - const std::string& signature) { - crypto::SignatureVerifier verifier; - - if (!verifier.VerifyInit(kSignatureAlgorithm, sizeof(kSignatureAlgorithm), - reinterpret_cast<const uint8*>(signature.c_str()), - signature.size(), - reinterpret_cast<const uint8*>(key.c_str()), - key.size())) { - return false; - } - verifier.VerifyUpdate(reinterpret_cast<const uint8*>(data.c_str()), - data.size()); - return verifier.VerifyFinal(); -} - -template class CloudPolicyValidator<em::CloudPolicySettings>; -template class CloudPolicyValidator<em::ExternalPolicyData>; - -} // namespace policy diff --git a/chrome/browser/policy/cloud/cloud_policy_validator.h b/chrome/browser/policy/cloud/cloud_policy_validator.h deleted file mode 100644 index 5b6ed4b..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_validator.h +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_VALIDATOR_H_ -#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_VALIDATOR_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/sequenced_task_runner.h" -#include "base/time/time.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "policy/proto/cloud_policy.pb.h" - -namespace base { -class MessageLoopProxy; -} - -namespace google { -namespace protobuf { -class MessageLite; -} -} - -namespace enterprise_management { -class PolicyData; -class PolicyFetchResponse; -} - -namespace policy { - -// Helper class that implements the gory details of validating a policy blob. -// Since signature checks are expensive, validation can happen on a background -// thread. The pattern is to create a validator, configure its behavior through -// the ValidateXYZ() functions, and then call StartValidation(). Alternatively, -// RunValidation() can be used to perform validation on the current thread. -class CloudPolicyValidatorBase { - public: - // Validation result codes. These values are also used for UMA histograms; - // they must stay stable, and the UMA counters must be updated if new elements - // are appended at the end. - enum Status { - // Indicates successful validation. - VALIDATION_OK, - // Bad signature on the initial key. - VALIDATION_BAD_INITIAL_SIGNATURE, - // Bad signature. - VALIDATION_BAD_SIGNATURE, - // Policy blob contains error code. - VALIDATION_ERROR_CODE_PRESENT, - // Policy payload failed to decode. - VALIDATION_PAYLOAD_PARSE_ERROR, - // Unexpected policy type. - VALIDATION_WRONG_POLICY_TYPE, - // Unexpected settings entity id. - VALIDATION_WRONG_SETTINGS_ENTITY_ID, - // Time stamp from the future. - VALIDATION_BAD_TIMESTAMP, - // Token doesn't match. - VALIDATION_WRONG_TOKEN, - // Username doesn't match. - VALIDATION_BAD_USERNAME, - // Policy payload protobuf parse error. - VALIDATION_POLICY_PARSE_ERROR, - }; - - enum ValidateDMTokenOption { - // The policy must have a non-empty DMToken. - DM_TOKEN_REQUIRED, - - // The policy may have an empty or missing DMToken, if the expected token - // is also empty. - DM_TOKEN_NOT_REQUIRED, - }; - - enum ValidateTimestampOption { - // The policy must have a timestamp field and it should be checked against - // both the start and end times. - TIMESTAMP_REQUIRED, - - // The timestamp should only be compared vs the |not_before| value (this - // is appropriate for platforms with unreliable system times, where we want - // to ensure that fresh policy is newer than existing policy, but we can't - // do any other validation). - TIMESTAMP_NOT_BEFORE, - - // No timestamp field is required. - TIMESTAMP_NOT_REQUIRED, - }; - - virtual ~CloudPolicyValidatorBase(); - - // Validation status which can be read after completion has been signaled. - Status status() const { return status_; } - bool success() const { return status_ == VALIDATION_OK; } - - // The policy objects owned by the validator. These are scoped_ptr - // references, so ownership can be passed on once validation is complete. - scoped_ptr<enterprise_management::PolicyFetchResponse>& policy() { - return policy_; - } - scoped_ptr<enterprise_management::PolicyData>& policy_data() { - return policy_data_; - } - - // Instructs the validator to check that the policy timestamp is not before - // |not_before| and not after |not_after| + grace interval. If - // |timestamp_option| is set to TIMESTAMP_REQUIRED, then the policy will fail - // validation if it does not have a timestamp field. - void ValidateTimestamp(base::Time not_before, - base::Time not_after, - ValidateTimestampOption timestamp_option); - - // Validates the username in the policy blob matches |expected_user|. - void ValidateUsername(const std::string& expected_user); - - // Validates the policy blob is addressed to |expected_domain|. This uses the - // domain part of the username field in the policy for the check. - void ValidateDomain(const std::string& expected_domain); - - // Makes sure the DM token on the policy matches |expected_token|. - // If |dm_token_option| is DM_TOKEN_REQUIRED, then the policy will fail - // validation if it does not have a non-empty request_token field. - void ValidateDMToken(const std::string& dm_token, - ValidateDMTokenOption dm_token_option); - - // Validates the policy type. - void ValidatePolicyType(const std::string& policy_type); - - // Validates the settings_entity_id value. - void ValidateSettingsEntityId(const std::string& settings_entity_id); - - // Validates that the payload can be decoded successfully. - void ValidatePayload(); - - // Verifies that the signature on the policy blob verifies against |key|. If | - // |allow_key_rotation| is true and there is a key rotation present in the - // policy blob, this checks the signature on the new key against |key| and the - // policy blob against the new key. - void ValidateSignature(const std::vector<uint8>& key, - bool allow_key_rotation); - - // Similar to StartSignatureVerification(), this checks the signature on the - // policy blob. However, this variant expects a new policy key set in the - // policy blob and makes sure the policy is signed using that key. This should - // be called at setup time when there is no existing policy key present to - // check against. - void ValidateInitialKey(); - - // Convenience helper that configures timestamp and token validation based on - // the current policy blob. |policy_data| may be NULL, in which case the - // timestamp validation will drop the lower bound. |dm_token_option| - // and |timestamp_option| have the same effect as the corresponding - // parameters for ValidateTimestamp() and ValidateDMToken(). - void ValidateAgainstCurrentPolicy( - const enterprise_management::PolicyData* policy_data, - ValidateTimestampOption timestamp_option, - ValidateDMTokenOption dm_token_option); - - // Immediately performs validation on the current thread. - void RunValidation(); - - protected: - // Create a new validator that checks |policy_response|. |payload| is the - // message that the policy payload will be parsed to, and it needs to stay - // valid for the lifetime of the validator. - CloudPolicyValidatorBase( - scoped_ptr<enterprise_management::PolicyFetchResponse> policy_response, - google::protobuf::MessageLite* payload, - scoped_refptr<base::SequencedTaskRunner> background_task_runner); - - // Posts an asynchronous calls to PerformValidation, which will eventually - // report its result via |completion_callback|. - void PostValidationTask(const base::Closure& completion_callback); - - private: - // Internal flags indicating what to check. - enum ValidationFlags { - VALIDATE_TIMESTAMP = 1 << 0, - VALIDATE_USERNAME = 1 << 1, - VALIDATE_DOMAIN = 1 << 2, - VALIDATE_TOKEN = 1 << 3, - VALIDATE_POLICY_TYPE = 1 << 4, - VALIDATE_ENTITY_ID = 1 << 5, - VALIDATE_PAYLOAD = 1 << 6, - VALIDATE_SIGNATURE = 1 << 7, - VALIDATE_INITIAL_KEY = 1 << 8, - }; - - // Performs validation, called on a background thread. - static void PerformValidation( - scoped_ptr<CloudPolicyValidatorBase> self, - scoped_refptr<base::MessageLoopProxy> message_loop, - const base::Closure& completion_callback); - - // Reports completion to the |completion_callback_|. - static void ReportCompletion(scoped_ptr<CloudPolicyValidatorBase> self, - const base::Closure& completion_callback); - - // Invokes all the checks and reports the result. - void RunChecks(); - - // Helper functions implementing individual checks. - Status CheckTimestamp(); - Status CheckUsername(); - Status CheckDomain(); - Status CheckToken(); - Status CheckPolicyType(); - Status CheckEntityId(); - Status CheckPayload(); - Status CheckSignature(); - Status CheckInitialKey(); - - // Verifies the SHA1/RSA |signature| on |data| against |key|. - static bool VerifySignature(const std::string& data, - const std::string& key, - const std::string& signature); - - Status status_; - scoped_ptr<enterprise_management::PolicyFetchResponse> policy_; - scoped_ptr<enterprise_management::PolicyData> policy_data_; - google::protobuf::MessageLite* payload_; - - int validation_flags_; - int64 timestamp_not_before_; - int64 timestamp_not_after_; - ValidateTimestampOption timestamp_option_; - ValidateDMTokenOption dm_token_option_; - std::string user_; - std::string domain_; - std::string token_; - std::string policy_type_; - std::string settings_entity_id_; - std::string key_; - bool allow_key_rotation_; - scoped_refptr<base::SequencedTaskRunner> background_task_runner_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidatorBase); -}; - -// A simple type-parameterized extension of CloudPolicyValidator that -// facilitates working with the actual protobuf payload type. -template<typename PayloadProto> -class CloudPolicyValidator : public CloudPolicyValidatorBase { - public: - typedef base::Callback<void(CloudPolicyValidator<PayloadProto>*)> - CompletionCallback; - - virtual ~CloudPolicyValidator() {} - - // Creates a new validator. - // |background_task_runner| is optional; if RunValidation() is used directly - // and StartValidation() is not used then it can be NULL. - static CloudPolicyValidator<PayloadProto>* Create( - scoped_ptr<enterprise_management::PolicyFetchResponse> policy_response, - scoped_refptr<base::SequencedTaskRunner> background_task_runner) { - return new CloudPolicyValidator( - policy_response.Pass(), - scoped_ptr<PayloadProto>(new PayloadProto()), - background_task_runner); - } - - scoped_ptr<PayloadProto>& payload() { - return payload_; - } - - // Kicks off asynchronous validation. |completion_callback| is invoked when - // done. From this point on, the validator manages its own lifetime - this - // allows callers to provide a WeakPtr in the callback without leaking the - // validator. - void StartValidation(const CompletionCallback& completion_callback) { - PostValidationTask(base::Bind(completion_callback, this)); - } - - private: - CloudPolicyValidator( - scoped_ptr<enterprise_management::PolicyFetchResponse> policy_response, - scoped_ptr<PayloadProto> payload, - scoped_refptr<base::SequencedTaskRunner> background_task_runner) - : CloudPolicyValidatorBase(policy_response.Pass(), - payload.get(), - background_task_runner), - payload_(payload.Pass()) {} - - scoped_ptr<PayloadProto> payload_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidator); -}; - -typedef CloudPolicyValidator<enterprise_management::CloudPolicySettings> - UserCloudPolicyValidator; -typedef CloudPolicyValidator<enterprise_management::ExternalPolicyData> - ComponentCloudPolicyValidator; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_VALIDATOR_H_ diff --git a/chrome/browser/policy/cloud/cloud_policy_validator_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_validator_unittest.cc deleted file mode 100644 index 88f9f48..0000000 --- a/chrome/browser/policy/cloud/cloud_policy_validator_unittest.cc +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <vector> - -#include "base/bind.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/message_loop/message_loop_proxy.h" -#include "base/strings/string_util.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "crypto/rsa_private_key.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace em = enterprise_management; - -using testing::Invoke; -using testing::Mock; - -namespace policy { - -namespace { - -ACTION_P(CheckStatus, expected_status) { - EXPECT_EQ(expected_status, arg0->status()); -}; - -class CloudPolicyValidatorTest : public testing::Test { - public: - CloudPolicyValidatorTest() - : loop_(base::MessageLoop::TYPE_UI), - timestamp_(base::Time::UnixEpoch() + - base::TimeDelta::FromMilliseconds( - PolicyBuilder::kFakeTimestamp)), - timestamp_option_(CloudPolicyValidatorBase::TIMESTAMP_REQUIRED), - ignore_missing_dm_token_(CloudPolicyValidatorBase::DM_TOKEN_REQUIRED), - allow_key_rotation_(true), - existing_dm_token_(PolicyBuilder::kFakeToken) { - policy_.SetDefaultNewSigningKey(); - } - - void Validate(testing::Action<void(UserCloudPolicyValidator*)> check_action) { - // Create a validator. - scoped_ptr<UserCloudPolicyValidator> validator = CreateValidator(); - - // Run validation and check the result. - EXPECT_CALL(*this, ValidationCompletion(validator.get())).WillOnce( - check_action); - validator.release()->StartValidation( - base::Bind(&CloudPolicyValidatorTest::ValidationCompletion, - base::Unretained(this))); - loop_.RunUntilIdle(); - Mock::VerifyAndClearExpectations(this); - } - - scoped_ptr<UserCloudPolicyValidator> CreateValidator() { - std::vector<uint8> public_key; - EXPECT_TRUE( - PolicyBuilder::CreateTestSigningKey()->ExportPublicKey(&public_key)); - policy_.Build(); - - UserCloudPolicyValidator* validator = UserCloudPolicyValidator::Create( - policy_.GetCopy(), base::MessageLoopProxy::current()); - validator->ValidateTimestamp(timestamp_, timestamp_, - timestamp_option_); - validator->ValidateUsername(PolicyBuilder::kFakeUsername); - validator->ValidateDomain(PolicyBuilder::kFakeDomain); - validator->ValidateDMToken(existing_dm_token_, ignore_missing_dm_token_); - validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType); - validator->ValidatePayload(); - validator->ValidateSignature(public_key, allow_key_rotation_); - if (allow_key_rotation_) - validator->ValidateInitialKey(); - return make_scoped_ptr(validator); - } - - - void CheckSuccessfulValidation(UserCloudPolicyValidator* validator) { - EXPECT_TRUE(validator->success()); - EXPECT_EQ(policy_.policy().SerializeAsString(), - validator->policy()->SerializeAsString()); - EXPECT_EQ(policy_.policy_data().SerializeAsString(), - validator->policy_data()->SerializeAsString()); - EXPECT_EQ(policy_.payload().SerializeAsString(), - validator->payload()->SerializeAsString()); - } - - base::MessageLoop loop_; - base::Time timestamp_; - CloudPolicyValidatorBase::ValidateTimestampOption timestamp_option_; - CloudPolicyValidatorBase::ValidateDMTokenOption ignore_missing_dm_token_; - std::string signing_key_; - bool allow_key_rotation_; - std::string existing_dm_token_; - - UserPolicyBuilder policy_; - - private: - MOCK_METHOD1(ValidationCompletion, void(UserCloudPolicyValidator* validator)); - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidatorTest); -}; - -TEST_F(CloudPolicyValidatorTest, SuccessfulValidation) { - Validate(Invoke(this, &CloudPolicyValidatorTest::CheckSuccessfulValidation)); -} - -TEST_F(CloudPolicyValidatorTest, SuccessfulRunValidation) { - scoped_ptr<UserCloudPolicyValidator> validator = CreateValidator(); - // Run validation immediately (no background tasks). - validator->RunValidation(); - CheckSuccessfulValidation(validator.get()); -} - -TEST_F(CloudPolicyValidatorTest, SuccessfulRunValidationWithNoExistingDMToken) { - existing_dm_token_.clear(); - Validate(Invoke(this, &CloudPolicyValidatorTest::CheckSuccessfulValidation)); -} - -TEST_F(CloudPolicyValidatorTest, SuccessfulRunValidationWithNoDMTokens) { - existing_dm_token_.clear(); - policy_.policy_data().clear_request_token(); - ignore_missing_dm_token_ = CloudPolicyValidatorBase::DM_TOKEN_NOT_REQUIRED; - Validate(Invoke(this, &CloudPolicyValidatorTest::CheckSuccessfulValidation)); -} - -TEST_F(CloudPolicyValidatorTest, UsernameCanonicalization) { - policy_.policy_data().set_username( - StringToUpperASCII(std::string(PolicyBuilder::kFakeUsername))); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_OK)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoPolicyType) { - policy_.policy_data().clear_policy_type(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_WRONG_POLICY_TYPE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorWrongPolicyType) { - policy_.policy_data().set_policy_type("invalid"); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_WRONG_POLICY_TYPE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoTimestamp) { - policy_.policy_data().clear_timestamp(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_TIMESTAMP)); -} - -TEST_F(CloudPolicyValidatorTest, IgnoreMissingTimestamp) { - timestamp_option_ = CloudPolicyValidatorBase::TIMESTAMP_NOT_REQUIRED; - policy_.policy_data().clear_timestamp(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_OK)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorOldTimestamp) { - base::Time timestamp(timestamp_ - base::TimeDelta::FromMinutes(5)); - policy_.policy_data().set_timestamp( - (timestamp - base::Time::UnixEpoch()).InMilliseconds()); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_TIMESTAMP)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorTimestampFromTheFuture) { - base::Time timestamp(timestamp_ + base::TimeDelta::FromMinutes(5)); - policy_.policy_data().set_timestamp( - (timestamp - base::Time::UnixEpoch()).InMilliseconds()); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_TIMESTAMP)); -} - -TEST_F(CloudPolicyValidatorTest, IgnoreErrorTimestampFromTheFuture) { - base::Time timestamp(timestamp_ + base::TimeDelta::FromMinutes(5)); - timestamp_option_ = - CloudPolicyValidatorBase::TIMESTAMP_NOT_BEFORE; - policy_.policy_data().set_timestamp( - (timestamp - base::Time::UnixEpoch()).InMilliseconds()); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_OK)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoRequestToken) { - policy_.policy_data().clear_request_token(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_WRONG_TOKEN)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoRequestTokenNotRequired) { - // Even though DMTokens are not required, if the existing policy has a token, - // we should still generate an error if the new policy has none. - policy_.policy_data().clear_request_token(); - ignore_missing_dm_token_ = CloudPolicyValidatorBase::DM_TOKEN_NOT_REQUIRED; - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_WRONG_TOKEN)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoRequestTokenNoTokenPassed) { - // Mimic the first fetch of policy (no existing DM token) - should still - // complain about not having any DMToken. - existing_dm_token_.clear(); - policy_.policy_data().clear_request_token(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_WRONG_TOKEN)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorInvalidRequestToken) { - policy_.policy_data().set_request_token("invalid"); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_WRONG_TOKEN)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoPolicyValue) { - policy_.clear_payload(); - Validate( - CheckStatus(CloudPolicyValidatorBase::VALIDATION_POLICY_PARSE_ERROR)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorInvalidPolicyValue) { - policy_.clear_payload(); - policy_.policy_data().set_policy_value("invalid"); - Validate( - CheckStatus(CloudPolicyValidatorBase::VALIDATION_POLICY_PARSE_ERROR)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoUsername) { - policy_.policy_data().clear_username(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_USERNAME)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorInvalidUsername) { - policy_.policy_data().set_username("invalid"); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_USERNAME)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorErrorMessage) { - policy_.policy().set_error_message("error"); - Validate( - CheckStatus(CloudPolicyValidatorBase::VALIDATION_ERROR_CODE_PRESENT)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorErrorCode) { - policy_.policy().set_error_code(42); - Validate( - CheckStatus(CloudPolicyValidatorBase::VALIDATION_ERROR_CODE_PRESENT)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoSignature) { - policy_.UnsetSigningKey(); - policy_.UnsetNewSigningKey(); - policy_.policy().clear_policy_data_signature(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorInvalidSignature) { - policy_.UnsetSigningKey(); - policy_.UnsetNewSigningKey(); - policy_.policy().set_policy_data_signature("invalid"); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoPublicKey) { - policy_.UnsetSigningKey(); - policy_.UnsetNewSigningKey(); - policy_.policy().clear_new_public_key(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorInvalidPublicKey) { - policy_.UnsetSigningKey(); - policy_.UnsetNewSigningKey(); - policy_.policy().set_new_public_key("invalid"); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoPublicKeySignature) { - policy_.UnsetSigningKey(); - policy_.UnsetNewSigningKey(); - policy_.policy().clear_new_public_key_signature(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorInvalidPublicKeySignature) { - policy_.UnsetSigningKey(); - policy_.UnsetNewSigningKey(); - policy_.policy().set_new_public_key_signature("invalid"); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, ErrorNoRotationAllowed) { - allow_key_rotation_ = false; - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE)); -} - -TEST_F(CloudPolicyValidatorTest, NoRotation) { - allow_key_rotation_ = false; - policy_.UnsetNewSigningKey(); - Validate(CheckStatus(CloudPolicyValidatorBase::VALIDATION_OK)); -} - -} // namespace - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc index b80ef5d..41e65ea 100644 --- a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc @@ -16,19 +16,19 @@ #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" #include "chrome/browser/policy/test/local_policy_test_server.h" -#include "chrome/browser/policy/test/policy_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_client.h" +#include "components/policy/core/common/policy_service.h" #include "components/policy/core/common/policy_switches.h" +#include "components/policy/core/common/policy_test_utils.h" #include "extensions/common/extension.h" #include "net/url_request/url_request_context_getter.h" #include "policy/proto/cloud_policy.pb.h" diff --git a/chrome/browser/policy/cloud/component_cloud_policy_service.cc b/chrome/browser/policy/cloud/component_cloud_policy_service.cc deleted file mode 100644 index f19b3ff..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_service.cc +++ /dev/null @@ -1,515 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_service.h" - -#include <string> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/message_loop/message_loop_proxy.h" -#include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/component_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/component_cloud_policy_updater.h" -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" -#include "chrome/browser/policy/cloud/resource_cache.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "components/policy/core/common/schema.h" -#include "components/policy/core/common/schema_map.h" -#include "net/url_request/url_request_context_getter.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -bool NotInSchemaMap(const scoped_refptr<SchemaMap> schema_map, - PolicyDomain domain, - const std::string& component_id) { - return schema_map->GetSchema(PolicyNamespace(domain, component_id)) == NULL; -} - -bool ToPolicyNamespaceKey(const PolicyNamespace& ns, PolicyNamespaceKey* key) { - if (!ComponentCloudPolicyStore::GetPolicyType(ns.domain, &key->first)) - return false; - key->second = ns.component_id; - return true; -} - -bool ToPolicyNamespace(const PolicyNamespaceKey& key, PolicyNamespace* ns) { - if (!ComponentCloudPolicyStore::GetPolicyDomain(key.first, &ns->domain)) - return false; - ns->component_id = key.second; - return true; -} - -} // namespace - -ComponentCloudPolicyService::Delegate::~Delegate() {} - -// Owns the objects that live on the background thread, and posts back to the -// thread that the ComponentCloudPolicyService runs on whenever the policy -// changes. -class ComponentCloudPolicyService::Backend - : public ComponentCloudPolicyStore::Delegate { - public: - // This class can be instantiated on any thread but from then on, may be - // accessed via the |task_runner_| only. Policy changes are posted to the - // |service| via the |service_task_runner|. The |cache| is used to load and - // store local copies of the downloaded policies. - Backend(base::WeakPtr<ComponentCloudPolicyService> service, - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_refptr<base::SequencedTaskRunner> service_task_runner, - scoped_ptr<ResourceCache> cache, - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher); - - virtual ~Backend(); - - // |username| and |dm_token| will be used to validate the cached policies. - void SetCredentials(const std::string& username, const std::string& dm_token); - - // Loads the |store_| and starts downloading updates. - void Init(scoped_refptr<SchemaMap> schema_map); - - // Passes a policy protobuf to the backend, to start its validation and - // eventual download of the policy data on the background thread. - void UpdateExternalPolicy(scoped_ptr<em::PolicyFetchResponse> response); - - // ComponentCloudPolicyStore::Delegate implementation: - virtual void OnComponentCloudPolicyStoreUpdated() OVERRIDE; - - // Passes the current SchemaMap so that the disk cache can purge components - // that aren't being tracked anymore. - // |removed| is a list of namespaces that were present in the previous - // schema and have been removed in the updated version. - void OnSchemasUpdated(scoped_refptr<SchemaMap> schema_map, - scoped_ptr<PolicyNamespaceList> removed); - - private: - // The ComponentCloudPolicyService that owns |this|. Used to inform the - // |service_| when policy changes. - base::WeakPtr<ComponentCloudPolicyService> service_; - - // The thread that |this| runs on. Used to post tasks to be run by |this|. - scoped_refptr<base::SequencedTaskRunner> task_runner_; - - // The thread that the |service_| runs on. Used to post policy changes to the - // right thread. - scoped_refptr<base::SequencedTaskRunner> service_task_runner_; - - scoped_ptr<ResourceCache> cache_; - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher_; - ComponentCloudPolicyStore store_; - scoped_ptr<ComponentCloudPolicyUpdater> updater_; - scoped_refptr<SchemaMap> schema_map_; - - DISALLOW_COPY_AND_ASSIGN(Backend); -}; - -ComponentCloudPolicyService::Backend::Backend( - base::WeakPtr<ComponentCloudPolicyService> service, - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_refptr<base::SequencedTaskRunner> service_task_runner, - scoped_ptr<ResourceCache> cache, - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher) - : service_(service), - task_runner_(task_runner), - service_task_runner_(service_task_runner), - cache_(cache.Pass()), - external_policy_data_fetcher_(external_policy_data_fetcher.Pass()), - store_(this, cache_.get()) {} - -ComponentCloudPolicyService::Backend::~Backend() {} - -void ComponentCloudPolicyService::Backend::SetCredentials( - const std::string& username, - const std::string& dm_token) { - if (username.empty() || dm_token.empty()) { - // No sign-in credentials, so drop any cached policy. - store_.Clear(); - } else { - store_.SetCredentials(username, dm_token); - } -} - -void ComponentCloudPolicyService::Backend::Init( - scoped_refptr<SchemaMap> schema_map) { - DCHECK(!schema_map_); - - OnSchemasUpdated(schema_map, scoped_ptr<PolicyNamespaceList>()); - - // Read the initial policy. Note that this does not trigger notifications - // through OnComponentCloudPolicyStoreUpdated. Note also that the cached - // data may contain names or values that don't match the schema for that - // component; the data must be cached without modifications so that its - // integrity can be verified using the hash, but it must also be filtered - // right after a Load(). - store_.Load(); - scoped_ptr<PolicyBundle> bundle(new PolicyBundle); - bundle->CopyFrom(store_.policy()); - schema_map_->FilterBundle(bundle.get()); - - // Start downloading any pending data. - updater_.reset(new ComponentCloudPolicyUpdater( - task_runner_, external_policy_data_fetcher_.Pass(), &store_)); - - service_task_runner_->PostTask( - FROM_HERE, - base::Bind(&ComponentCloudPolicyService::OnBackendInitialized, - service_, - base::Passed(&bundle))); -} - -void ComponentCloudPolicyService::Backend::UpdateExternalPolicy( - scoped_ptr<em::PolicyFetchResponse> response) { - updater_->UpdateExternalPolicy(response.Pass()); -} - -void ComponentCloudPolicyService::Backend:: - OnComponentCloudPolicyStoreUpdated() { - if (!schema_map_) { - // Ignore notifications triggered by the initial Purge or Clear. - return; - } - - scoped_ptr<PolicyBundle> bundle(new PolicyBundle); - bundle->CopyFrom(store_.policy()); - schema_map_->FilterBundle(bundle.get()); - service_task_runner_->PostTask( - FROM_HERE, - base::Bind(&ComponentCloudPolicyService::OnPolicyUpdated, - service_, - base::Passed(&bundle))); -} - -void ComponentCloudPolicyService::Backend::OnSchemasUpdated( - scoped_refptr<SchemaMap> schema_map, - scoped_ptr<PolicyNamespaceList> removed) { - // Purge any components that have been removed. - const DomainMap& domains = schema_map->GetDomains(); - for (DomainMap::const_iterator domain = domains.begin(); - domain != domains.end(); ++domain) { - store_.Purge(domain->first, - base::Bind(&NotInSchemaMap, schema_map, domain->first)); - } - - // Set |schema_map_| after purging so that the notifications from the store - // are ignored on the first OnSchemasUpdated() call from Init(). - schema_map_ = schema_map; - - if (removed) { - for (size_t i = 0; i < removed->size(); ++i) - updater_->CancelUpdate((*removed)[i]); - } -} - -ComponentCloudPolicyService::ComponentCloudPolicyService( - Delegate* delegate, - SchemaRegistry* schema_registry, - CloudPolicyCore* core, - scoped_ptr<ResourceCache> cache, - scoped_refptr<net::URLRequestContextGetter> request_context, - scoped_refptr<base::SequencedTaskRunner> backend_task_runner, - scoped_refptr<base::SequencedTaskRunner> io_task_runner) - : delegate_(delegate), - schema_registry_(schema_registry), - core_(core), - request_context_(request_context), - backend_task_runner_(backend_task_runner), - io_task_runner_(io_task_runner), - current_schema_map_(new SchemaMap), - started_loading_initial_policy_(false), - loaded_initial_policy_(false), - is_registered_for_cloud_policy_(false), - weak_ptr_factory_(this) { - external_policy_data_fetcher_backend_.reset( - new ExternalPolicyDataFetcherBackend(io_task_runner_, request_context)); - - backend_.reset( - new Backend(weak_ptr_factory_.GetWeakPtr(), - backend_task_runner_, - base::MessageLoopProxy::current(), - cache.Pass(), - external_policy_data_fetcher_backend_->CreateFrontend( - backend_task_runner_))); - - schema_registry_->AddObserver(this); - core_->store()->AddObserver(this); - - // Wait for the store and the schema registry to become ready before - // initializing the backend, so that it can get the initial list of - // components and the cached credentials (if any) to validate the cached - // policies. - if (core_->store()->is_initialized()) - OnStoreLoaded(core_->store()); -} - -ComponentCloudPolicyService::~ComponentCloudPolicyService() { - DCHECK(CalledOnValidThread()); - - schema_registry_->RemoveObserver(this); - core_->store()->RemoveObserver(this); - core_->RemoveObserver(this); - if (core_->client()) - OnCoreDisconnecting(core_); - - io_task_runner_->DeleteSoon(FROM_HERE, - external_policy_data_fetcher_backend_.release()); - backend_task_runner_->DeleteSoon(FROM_HERE, backend_.release()); -} - -// static -bool ComponentCloudPolicyService::SupportsDomain(PolicyDomain domain) { - return ComponentCloudPolicyStore::SupportsDomain(domain); -} - -void ComponentCloudPolicyService::ClearCache() { - DCHECK(CalledOnValidThread()); - // Empty credentials will wipe the cache. - backend_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::SetCredentials, - base::Unretained(backend_.get()), - std::string(), std::string())); -} - -void ComponentCloudPolicyService::OnSchemaRegistryReady() { - DCHECK(CalledOnValidThread()); - InitializeIfReady(); -} - -void ComponentCloudPolicyService::OnSchemaRegistryUpdated( - bool has_new_schemas) { - DCHECK(CalledOnValidThread()); - - // Ignore schema updates until the backend is initialized. - // OnBackendInitialized() will send the current schema to the backend again, - // in case it was updated before the backend initialized. - if (!loaded_initial_policy_) - return; - - SetCurrentSchema(); -} - -void ComponentCloudPolicyService::OnCoreConnected(CloudPolicyCore* core) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(core_, core); - - core_->client()->AddObserver(this); - - // Immediately load any PolicyFetchResponses that the client may already - // have. - OnPolicyFetched(core_->client()); - - // Register the current namespaces at the client. - current_schema_map_ = new SchemaMap(); - SetCurrentSchema(); -} - -void ComponentCloudPolicyService::OnCoreDisconnecting(CloudPolicyCore* core) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(core_, core); - - core_->client()->RemoveObserver(this); - - // Remove all the namespaces from the client. - scoped_refptr<SchemaMap> empty = new SchemaMap(); - PolicyNamespaceList removed; - PolicyNamespaceList added; - empty->GetChanges(current_schema_map_, &removed, &added); - for (size_t i = 0; i < removed.size(); ++i) { - PolicyNamespaceKey key; - if (ToPolicyNamespaceKey(removed[i], &key)) - core_->client()->RemoveNamespaceToFetch(key); - } -} - -void ComponentCloudPolicyService::OnRefreshSchedulerStarted( - CloudPolicyCore* core) { - // Ignored. -} - -void ComponentCloudPolicyService::OnStoreLoaded(CloudPolicyStore* store) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(core_->store(), store); - - const bool was_registered_before = is_registered_for_cloud_policy_; - - // Send the current credentials to the backend; do this whenever the store - // updates, to handle the case of the user registering for policy after the - // session starts, or the user signing out. - const em::PolicyData* policy = core_->store()->policy(); - std::string username; - std::string request_token; - if (policy && policy->has_username() && policy->has_request_token()) { - is_registered_for_cloud_policy_ = true; - username = policy->username(); - request_token = policy->request_token(); - } else { - is_registered_for_cloud_policy_ = false; - } - - // Empty credentials will wipe the cache. - backend_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::SetCredentials, - base::Unretained(backend_.get()), - username, - request_token)); - - if (!loaded_initial_policy_) { - // This is the initial load; check if we're ready to initialize the - // backend, regardless of the signin state. - InitializeIfReady(); - } else if (!was_registered_before && is_registered_for_cloud_policy_) { - // We are already initialized, but just sent credentials to the backend for - // the first time; this means that the user was not registered for cloud - // policy on startup but registered during the session. - // - // When that happens, OnPolicyFetched() is sent to observers before the - // CloudPolicyStore gets a chance to verify the user policy. In those cases, - // the backend gets the PolicyFetchResponses before it has the credentials - // and therefore the validation of those responses fails. - // Reload any PolicyFetchResponses that the client may have now so that - // validation is retried with the credentials in place. - if (core_->client()) - OnPolicyFetched(core_->client()); - } -} - -void ComponentCloudPolicyService::OnStoreError(CloudPolicyStore* store) { - DCHECK(CalledOnValidThread()); - OnStoreLoaded(store); -} - -void ComponentCloudPolicyService::OnPolicyFetched(CloudPolicyClient* client) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(core_->client(), client); - - if (!is_registered_for_cloud_policy_) { - // Trying to load any policies now will fail validation. An OnStoreLoaded() - // notification should follow soon, after the main user policy has been - // validated and stored. - return; - } - - // Pass each PolicyFetchResponse whose policy type is registered to the - // Backend. - const CloudPolicyClient::ResponseMap& responses = - core_->client()->responses(); - for (CloudPolicyClient::ResponseMap::const_iterator it = responses.begin(); - it != responses.end(); ++it) { - PolicyNamespace ns; - if (ToPolicyNamespace(it->first, &ns) && - current_schema_map_->GetSchema(ns)) { - scoped_ptr<em::PolicyFetchResponse> response( - new em::PolicyFetchResponse(*it->second)); - backend_task_runner_->PostTask( - FROM_HERE, - base::Bind(&Backend::UpdateExternalPolicy, - base::Unretained(backend_.get()), - base::Passed(&response))); - } - } -} - -void ComponentCloudPolicyService::OnRegistrationStateChanged( - CloudPolicyClient* client) { - DCHECK(CalledOnValidThread()); - // Ignored; the registration state is tracked by looking at the - // CloudPolicyStore instead. -} - -void ComponentCloudPolicyService::OnClientError(CloudPolicyClient* client) { - DCHECK(CalledOnValidThread()); - // Ignored. -} - -void ComponentCloudPolicyService::InitializeIfReady() { - DCHECK(CalledOnValidThread()); - if (started_loading_initial_policy_ || !schema_registry_->IsReady() || - !core_->store()->is_initialized()) { - return; - } - // The initial list of components is ready. Initialize the backend now, which - // will call back to OnBackendInitialized. - backend_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::Init, - base::Unretained(backend_.get()), - schema_registry_->schema_map())); - started_loading_initial_policy_ = true; -} - -void ComponentCloudPolicyService::OnBackendInitialized( - scoped_ptr<PolicyBundle> initial_policy) { - DCHECK(CalledOnValidThread()); - DCHECK(!loaded_initial_policy_); - - loaded_initial_policy_ = true; - - // We're now ready to serve the initial policy; notify the policy observers. - OnPolicyUpdated(initial_policy.Pass()); - - // Start observing the core and tracking the state of the client. - core_->AddObserver(this); - - if (core_->client()) { - OnCoreConnected(core_); - } else { - // Send the current schema to the backend, in case it has changed while the - // backend was initializing. OnCoreConnected() also does this if a client is - // already connected. - SetCurrentSchema(); - } -} - -void ComponentCloudPolicyService::SetCurrentSchema() { - DCHECK(CalledOnValidThread()); - - scoped_ptr<PolicyNamespaceList> removed(new PolicyNamespaceList); - PolicyNamespaceList added; - const scoped_refptr<SchemaMap>& new_schema_map = - schema_registry_->schema_map(); - new_schema_map->GetChanges(current_schema_map_, removed.get(), &added); - - current_schema_map_ = new_schema_map; - - if (core_->client()) { - for (size_t i = 0; i < removed->size(); ++i) { - PolicyNamespaceKey key; - if (ToPolicyNamespaceKey((*removed)[i], &key)) - core_->client()->RemoveNamespaceToFetch(key); - } - - bool added_namespaces_to_client = false; - for (size_t i = 0; i < added.size(); ++i) { - PolicyNamespaceKey key; - if (ToPolicyNamespaceKey(added[i], &key)) { - core_->client()->AddNamespaceToFetch(key); - added_namespaces_to_client = true; - } - } - - if (added_namespaces_to_client) - core_->RefreshSoon(); - } - - backend_task_runner_->PostTask(FROM_HERE, - base::Bind(&Backend::OnSchemasUpdated, - base::Unretained(backend_.get()), - current_schema_map_, - base::Passed(&removed))); -} - -void ComponentCloudPolicyService::OnPolicyUpdated( - scoped_ptr<PolicyBundle> policy) { - DCHECK(CalledOnValidThread()); - policy_.Swap(policy.get()); - delegate_->OnComponentCloudPolicyUpdated(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_service.h b/chrome/browser/policy/cloud/component_cloud_policy_service.h deleted file mode 100644 index 95ae7ed..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_service.h +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_SERVICE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_SERVICE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/non_thread_safe.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_namespace.h" -#include "components/policy/core/common/schema_registry.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -class ExternalPolicyDataFetcherBackend; -class ResourceCache; -class SchemaMap; - -// Manages cloud policy for components. -// -// This class takes care of fetching, validating, storing and updating policy -// for components. The components to manage come from a SchemaRegistry. -class ComponentCloudPolicyService : public CloudPolicyClient::Observer, - public CloudPolicyCore::Observer, - public CloudPolicyStore::Observer, - public SchemaRegistry::Observer, - public base::NonThreadSafe { - public: - class Delegate { - public: - virtual ~Delegate(); - - // Invoked whenever the policy served by policy() changes. This is also - // invoked for the first time once the backend is initialized, and - // is_initialized() becomes true. - virtual void OnComponentCloudPolicyUpdated() = 0; - }; - - // The |delegate| is notified of updates to the downloaded policies and must - // outlive this object. - // - // |schema_registry| is used to get the list of components to fetch cloud - // policy for. It must outlive this object. - // - // |core| is used to obtain the CloudPolicyStore and CloudPolicyClient used - // by this service. The store will be the source of the registration status - // and registration credentials; the client will be used to fetch cloud - // policy. It must outlive this object. - // - // |cache| is used to load and store local copies of the downloaded policies. - // - // Download scheduling, validation and caching of policies are done via the - // |backend_task_runner|, which must support file I/O. Network I/O is done via - // the |io_task_runner|. - // - // |request_context| is used by the background URLFetchers. - ComponentCloudPolicyService( - Delegate* delegate, - SchemaRegistry* schema_registry, - CloudPolicyCore* core, -#if !defined(OS_ANDROID) && !defined(OS_IOS) - scoped_ptr<ResourceCache> cache, -#endif - scoped_refptr<net::URLRequestContextGetter> request_context, - scoped_refptr<base::SequencedTaskRunner> backend_task_runner, - scoped_refptr<base::SequencedTaskRunner> io_task_runner); - virtual ~ComponentCloudPolicyService(); - - // Returns true if |domain| is supported by the service. - static bool SupportsDomain(PolicyDomain domain); - - // Returns true if the backend is initialized, and the initial policies and - // components are being served. - bool is_initialized() const { return loaded_initial_policy_; } - - // Returns the current policies for components. - const PolicyBundle& policy() const { return policy_; } - - // Deletes all the cached component policy. - void ClearCache(); - - // SchemaRegistry::Observer implementation: - virtual void OnSchemaRegistryReady() OVERRIDE; - virtual void OnSchemaRegistryUpdated(bool has_new_schemas) OVERRIDE; - - // CloudPolicyCore::Observer implementation: - virtual void OnCoreConnected(CloudPolicyCore* core) OVERRIDE; - virtual void OnCoreDisconnecting(CloudPolicyCore* core) OVERRIDE; - virtual void OnRefreshSchedulerStarted(CloudPolicyCore* core) OVERRIDE; - - // CloudPolicyStore::Observer implementation: - virtual void OnStoreLoaded(CloudPolicyStore* store) OVERRIDE; - virtual void OnStoreError(CloudPolicyStore* store) OVERRIDE; - - // CloudPolicyClient::Observer implementation: - virtual void OnPolicyFetched(CloudPolicyClient* client) OVERRIDE; - virtual void OnRegistrationStateChanged(CloudPolicyClient* client) OVERRIDE; - virtual void OnClientError(CloudPolicyClient* client) OVERRIDE; - - private: -#if !defined(OS_ANDROID) && !defined(OS_IOS) - class Backend; - - void InitializeIfReady(); - void OnBackendInitialized(scoped_ptr<PolicyBundle> initial_policy); - void SetCurrentSchema(); - void OnPolicyUpdated(scoped_ptr<PolicyBundle> policy); - - Delegate* delegate_; - SchemaRegistry* schema_registry_; - CloudPolicyCore* core_; - scoped_refptr<net::URLRequestContextGetter> request_context_; - scoped_refptr<base::SequencedTaskRunner> backend_task_runner_; - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - - // The |external_policy_data_fetcher_backend_| handles network I/O for the - // |backend_| because URLRequestContextGetter and URLFetchers cannot be - // referenced from background threads. It is instantiated on the thread |this| - // runs on but after that, must only be accessed and eventually destroyed via - // the |io_task_runner_|. - scoped_ptr<ExternalPolicyDataFetcherBackend> - external_policy_data_fetcher_backend_; - - // The |backend_| handles all download scheduling, validation and caching of - // policies. It is instantiated on the thread |this| runs on but after that, - // must only be accessed and eventually destroyed via the - // |backend_task_runner_|. - scoped_ptr<Backend> backend_; - - // The currently registered components for each policy domain. Used to - // determine which components changed when a new SchemaMap becomes - // available. - scoped_refptr<SchemaMap> current_schema_map_; -#endif // !defined(OS_ANDROID) && !defined(OS_IOS) - - // Contains all the current policies for components. - PolicyBundle policy_; - - // Whether the backend has started initializing asynchronously. Used to - // prevent double initialization, since both OnSchemaRegistryUpdated() and - // OnStoreLoaded() can happen while the backend is initializing. - bool started_loading_initial_policy_; - - // Whether the backend has been initialized with the initial credentials and - // schemas, and this provider is serving the initial policies loaded from the - // cache. - bool loaded_initial_policy_; - - // True if the backend currently has valid cloud policy credentials. This - // can go back to false if the user signs out, and back again to true if the - // user signs in again. - bool is_registered_for_cloud_policy_; - - base::WeakPtrFactory<ComponentCloudPolicyService> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(ComponentCloudPolicyService); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_SERVICE_H_ diff --git a/chrome/browser/policy/cloud/component_cloud_policy_service_stub.cc b/chrome/browser/policy/cloud/component_cloud_policy_service_stub.cc deleted file mode 100644 index 35ebc45..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_service_stub.cc +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_service.h" - -#include "base/sequenced_task_runner.h" -#include "net/url_request/url_request_context_getter.h" - -namespace policy { - -ComponentCloudPolicyService::Delegate::~Delegate() {} - -ComponentCloudPolicyService::ComponentCloudPolicyService( - Delegate* delegate, - SchemaRegistry* schema_registry, - CloudPolicyCore* core, - scoped_refptr<net::URLRequestContextGetter> request_context, - scoped_refptr<base::SequencedTaskRunner> backend_task_runner, - scoped_refptr<base::SequencedTaskRunner> io_task_runner) - : started_loading_initial_policy_(false), - loaded_initial_policy_(true), - is_registered_for_cloud_policy_(false), - weak_ptr_factory_(this) {} - -ComponentCloudPolicyService::~ComponentCloudPolicyService() {} - -// static -bool ComponentCloudPolicyService::SupportsDomain(PolicyDomain domain) { - return false; -} - -void ComponentCloudPolicyService::OnSchemaRegistryReady() {} - -void ComponentCloudPolicyService::OnSchemaRegistryUpdated( - bool has_new_schemas) {} - -void ComponentCloudPolicyService::OnCoreConnected(CloudPolicyCore* core) {} - -void ComponentCloudPolicyService::OnCoreDisconnecting(CloudPolicyCore* core) {} - -void ComponentCloudPolicyService::OnRefreshSchedulerStarted( - CloudPolicyCore* core) {} - -void ComponentCloudPolicyService::OnStoreLoaded(CloudPolicyStore* store) {} - -void ComponentCloudPolicyService::OnStoreError(CloudPolicyStore* store) {} - -void ComponentCloudPolicyService::OnPolicyFetched(CloudPolicyClient* client) {} - -void ComponentCloudPolicyService::OnRegistrationStateChanged( - CloudPolicyClient* client) {} - -void ComponentCloudPolicyService::OnClientError(CloudPolicyClient* client) {} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_service_unittest.cc b/chrome/browser/policy/cloud/component_cloud_policy_service_unittest.cc deleted file mode 100644 index e40855a..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_service_unittest.cc +++ /dev/null @@ -1,554 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_service.h" - -#include <map> -#include <string> - -#include "base/callback.h" -#include "base/files/scoped_temp_dir.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "base/sha1.h" -#include "base/single_thread_task_runner.h" -#include "base/stl_util.h" -#include "base/values.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "chrome/browser/policy/cloud/resource_cache.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_types.h" -#include "components/policy/core/common/schema.h" -#include "components/policy/core/common/schema_map.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_getter.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace em = enterprise_management; - -using testing::Mock; - -namespace policy { - -namespace { - -const char kTestExtension[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; -const char kTestExtension2[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; -const char kTestDownload[] = "http://example.com/getpolicy?id=123"; - -const char kTestPolicy[] = - "{" - " \"Name\": {" - " \"Value\": \"disabled\"" - " }," - " \"Second\": {" - " \"Value\": \"maybe\"," - " \"Level\": \"Recommended\"" - " }" - "}"; - -const char kInvalidTestPolicy[] = - "{" - " \"Name\": {" - " \"Value\": \"published\"" - " }," - " \"Undeclared Name\": {" - " \"Value\": \"not published\"" - " }" - "}"; - -const char kTestSchema[] = - "{" - " \"type\": \"object\"," - " \"properties\": {" - " \"Name\": { \"type\": \"string\" }," - " \"Second\": { \"type\": \"string\" }" - " }" - "}"; - -class MockComponentCloudPolicyDelegate - : public ComponentCloudPolicyService::Delegate { - public: - virtual ~MockComponentCloudPolicyDelegate() {} - - MOCK_METHOD0(OnComponentCloudPolicyUpdated, void()); -}; - -class TestURLRequestContextGetter : public net::URLRequestContextGetter { - public: - explicit TestURLRequestContextGetter( - scoped_refptr<base::SingleThreadTaskRunner> task_runner) - : task_runner_(task_runner) {} - virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE { - return NULL; - } - virtual scoped_refptr<base::SingleThreadTaskRunner> - GetNetworkTaskRunner() const OVERRIDE { - return task_runner_; - } - - private: - virtual ~TestURLRequestContextGetter() {} - - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; -}; - -} // namespace - -class ComponentCloudPolicyServiceTest : public testing::Test { - protected: - ComponentCloudPolicyServiceTest() - : client_(NULL), - core_(PolicyNamespaceKey(GetChromeUserPolicyType(), ""), - &store_, - loop_.message_loop_proxy()) {} - - virtual void SetUp() OVERRIDE { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - - cache_ = new ResourceCache(temp_dir_.path(), loop_.message_loop_proxy()); - request_context_ = - new TestURLRequestContextGetter(loop_.message_loop_proxy()); - service_.reset(new ComponentCloudPolicyService( - &delegate_, - ®istry_, - &core_, - make_scoped_ptr(cache_), - request_context_, - loop_.message_loop_proxy(), - loop_.message_loop_proxy())); - - builder_.policy_data().set_policy_type( - dm_protocol::kChromeExtensionPolicyType); - builder_.policy_data().set_settings_entity_id(kTestExtension); - builder_.payload().set_download_url(kTestDownload); - builder_.payload().set_secure_hash(base::SHA1HashString(kTestPolicy)); - - expected_policy_.Set("Name", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("disabled"), NULL); - expected_policy_.Set("Second", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - base::Value::CreateStringValue("maybe"), NULL); - } - - virtual void TearDown() OVERRIDE { - // The service cleans up its backend on the background thread. - service_.reset(); - RunUntilIdle(); - } - - void RunUntilIdle() { - base::RunLoop().RunUntilIdle(); - } - - void Connect(size_t expected_namespaces_in_client) { - client_ = new MockCloudPolicyClient(); - client_->SetDMToken(ComponentPolicyBuilder::kFakeToken); - EXPECT_EQ(0u, client_->namespaces_to_fetch_.size()); - - core_.Connect(scoped_ptr<CloudPolicyClient>(client_)); - - // |expected_namespaces_in_client| is the expected number of components - // that the ComponentCloudPolicyService will set at the |client_| at - // OnCoreConnected. - EXPECT_EQ(expected_namespaces_in_client, - client_->namespaces_to_fetch_.size()); - - // Also initialize the refresh scheduler, so that calls to - // core()->RefreshSoon() trigger a FetchPolicy() call on the mock |client_|. - // Expect the initial refresh now, if the store doesn't have policy (if it - // does then the CloudPolicyRefreshScheduler won't start refreshing until - // invalidations are available, or a timeout elapses). - if (!store_.has_policy()) - EXPECT_CALL(*client_, FetchPolicy()); - core_.StartRefreshScheduler(); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(client_); - } - - void LoadStore() { - EXPECT_FALSE(store_.is_initialized()); - - em::PolicyData* data = new em::PolicyData(); - data->set_username(ComponentPolicyBuilder::kFakeUsername); - data->set_request_token(ComponentPolicyBuilder::kFakeToken); - store_.policy_.reset(data); - - store_.NotifyStoreLoaded(); - RunUntilIdle(); - EXPECT_TRUE(store_.is_initialized()); - } - - void InitializeRegistry() { - registry_.RegisterComponent( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kTestExtension), - CreateTestSchema()); - registry_.SetReady(POLICY_DOMAIN_CHROME); - registry_.SetReady(POLICY_DOMAIN_EXTENSIONS); - } - - void PopulateCache() { - EXPECT_TRUE(cache_->Store( - "extension-policy", kTestExtension, CreateSerializedResponse())); - EXPECT_TRUE( - cache_->Store("extension-policy-data", kTestExtension, kTestPolicy)); - - builder_.policy_data().set_settings_entity_id(kTestExtension2); - EXPECT_TRUE(cache_->Store( - "extension-policy", kTestExtension2, CreateSerializedResponse())); - EXPECT_TRUE( - cache_->Store("extension-policy-data", kTestExtension2, kTestPolicy)); - } - - scoped_ptr<em::PolicyFetchResponse> CreateResponse() { - builder_.Build(); - return make_scoped_ptr(new em::PolicyFetchResponse(builder_.policy())); - } - - std::string CreateSerializedResponse() { - builder_.Build(); - return builder_.GetBlob(); - } - - Schema CreateTestSchema() { - std::string error; - Schema schema = Schema::Parse(kTestSchema, &error); - EXPECT_TRUE(schema.valid()) << error; - return schema; - } - - base::MessageLoop loop_; - base::ScopedTempDir temp_dir_; - scoped_refptr<TestURLRequestContextGetter> request_context_; - net::TestURLFetcherFactory fetcher_factory_; - MockComponentCloudPolicyDelegate delegate_; - // |cache_| is owned by the |service_| and is invalid once the |service_| - // is destroyed. - ResourceCache* cache_; - MockCloudPolicyClient* client_; - MockCloudPolicyStore store_; - CloudPolicyCore core_; - SchemaRegistry registry_; - scoped_ptr<ComponentCloudPolicyService> service_; - ComponentPolicyBuilder builder_; - PolicyMap expected_policy_; -}; - -TEST_F(ComponentCloudPolicyServiceTest, InitializedAtConstructionTime) { - service_.reset(); - Connect(1u); - LoadStore(); - InitializeRegistry(); - - cache_ = new ResourceCache(temp_dir_.path(), loop_.message_loop_proxy()); - service_.reset(new ComponentCloudPolicyService(&delegate_, - ®istry_, - &core_, - make_scoped_ptr(cache_), - request_context_, - loop_.message_loop_proxy(), - loop_.message_loop_proxy())); - EXPECT_FALSE(service_->is_initialized()); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - EXPECT_CALL(*client_, FetchPolicy()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&client_); - Mock::VerifyAndClearExpectations(&delegate_); - - EXPECT_TRUE(service_->is_initialized()); - EXPECT_EQ(2u, client_->namespaces_to_fetch_.size()); - const PolicyBundle empty_bundle; - EXPECT_TRUE(service_->policy().Equals(empty_bundle)); -} - -TEST_F(ComponentCloudPolicyServiceTest, InitializeStoreThenRegistry) { - Connect(1u); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()).Times(0); - EXPECT_CALL(*client_, FetchPolicy()).Times(0); - LoadStore(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - EXPECT_FALSE(service_->is_initialized()); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - EXPECT_CALL(*client_, FetchPolicy()); - InitializeRegistry(); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - EXPECT_TRUE(service_->is_initialized()); - - const PolicyBundle empty_bundle; - EXPECT_TRUE(service_->policy().Equals(empty_bundle)); -} - -TEST_F(ComponentCloudPolicyServiceTest, InitializeRegistryThenStore) { - Connect(1u); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()).Times(0); - EXPECT_CALL(*client_, FetchPolicy()).Times(0); - InitializeRegistry(); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - EXPECT_FALSE(service_->is_initialized()); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - EXPECT_CALL(*client_, FetchPolicy()); - LoadStore(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - EXPECT_TRUE(service_->is_initialized()); - EXPECT_EQ(2u, client_->namespaces_to_fetch_.size()); - const PolicyBundle empty_bundle; - EXPECT_TRUE(service_->policy().Equals(empty_bundle)); -} - -TEST_F(ComponentCloudPolicyServiceTest, InitializeWithCachedPolicy) { - PopulateCache(); - Connect(1u); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - EXPECT_CALL(*client_, FetchPolicy()); - InitializeRegistry(); - LoadStore(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - - EXPECT_TRUE(service_->is_initialized()); - EXPECT_EQ(2u, client_->namespaces_to_fetch_.size()); - - // kTestExtension2 is not in the registry so it was dropped. - std::map<std::string, std::string> contents; - cache_->LoadAllSubkeys("extension-policy", &contents); - ASSERT_EQ(1u, contents.size()); - EXPECT_EQ(kTestExtension, contents.begin()->first); - - PolicyBundle expected_bundle; - const PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - expected_bundle.Get(ns).CopyFrom(expected_policy_); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); -} - -TEST_F(ComponentCloudPolicyServiceTest, FetchPolicy) { - Connect(1u); - // Initialize the store and create the backend. - // A refresh is not needed, because no components are registered yet. - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - EXPECT_CALL(*client_, FetchPolicy()).Times(0); - registry_.SetReady(POLICY_DOMAIN_CHROME); - registry_.SetReady(POLICY_DOMAIN_EXTENSIONS); - LoadStore(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - EXPECT_TRUE(service_->is_initialized()); - - // Register the components to fetch. - EXPECT_CALL(*client_, FetchPolicy()); - registry_.RegisterComponent( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kTestExtension), - CreateTestSchema()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(client_); - - // Send back a fake policy fetch response. - client_->SetPolicy(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType, - kTestExtension), - *CreateResponse()); - service_->OnPolicyFetched(client_); - RunUntilIdle(); - - // That should have triggered the download fetch. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL()); - fetcher->set_response_code(200); - fetcher->SetResponseString(kTestPolicy); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - - // The policy is now being served. - const PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - PolicyBundle expected_bundle; - expected_bundle.Get(ns).CopyFrom(expected_policy_); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); -} - -TEST_F(ComponentCloudPolicyServiceTest, LoadAndPurgeCache) { - Connect(1u); - // Insert data in the cache. - PopulateCache(); - registry_.RegisterComponent( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kTestExtension2), - CreateTestSchema()); - InitializeRegistry(); - - // Load the initial cache. - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - EXPECT_CALL(*client_, FetchPolicy()); - LoadStore(); - Mock::VerifyAndClearExpectations(client_); - Mock::VerifyAndClearExpectations(&delegate_); - - PolicyBundle expected_bundle; - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - expected_bundle.Get(ns).CopyFrom(expected_policy_); - ns.component_id = kTestExtension2; - expected_bundle.Get(ns).CopyFrom(expected_policy_); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); - - // Now purge one of the extensions. - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - registry_.UnregisterComponent( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kTestExtension)); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - - ns.component_id = kTestExtension; - expected_bundle.Get(ns).Clear(); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); - - std::map<std::string, std::string> contents; - cache_->LoadAllSubkeys("extension-policy", &contents); - EXPECT_EQ(1u, contents.size()); - EXPECT_TRUE(ContainsKey(contents, kTestExtension2)); -} - -TEST_F(ComponentCloudPolicyServiceTest, SignInAfterStartup) { - registry_.SetReady(POLICY_DOMAIN_CHROME); - registry_.SetReady(POLICY_DOMAIN_EXTENSIONS); - - // Initialize the store without credentials. - EXPECT_FALSE(store_.is_initialized()); - EXPECT_FALSE(service_->is_initialized()); - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - store_.NotifyStoreLoaded(); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - EXPECT_TRUE(service_->is_initialized()); - - // Register an extension. - registry_.RegisterComponent( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kTestExtension), - CreateTestSchema()); - RunUntilIdle(); - - // Now signin. A fetch will be requested for the new extension. - Connect(2u); - - // Send the response to the service. The response data will be ignored, - // because the store doesn't have the updated credentials yet. - client_->SetPolicy(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType, - kTestExtension), - *CreateResponse()); - service_->OnPolicyFetched(client_); - RunUntilIdle(); - - // The policy was ignored and no download is started because the store - // doesn't have credentials. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - EXPECT_FALSE(fetcher); - - // Now update the |store_| with the updated policy, which includes - // credentials. The responses in the |client_| will be reloaded. - em::PolicyData* data = new em::PolicyData(); - data->set_username(ComponentPolicyBuilder::kFakeUsername); - data->set_request_token(ComponentPolicyBuilder::kFakeToken); - store_.policy_.reset(data); - store_.NotifyStoreLoaded(); - RunUntilIdle(); - - // The extension policy was validated this time, and the download is started. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL()); - fetcher->set_response_code(200); - fetcher->SetResponseString(kTestPolicy); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - - // The policy is now being served. - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - PolicyBundle expected_bundle; - expected_bundle.Get(ns).CopyFrom(expected_policy_); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); -} - -TEST_F(ComponentCloudPolicyServiceTest, SignOut) { - // Initialize everthing and serve policy for a component. - PopulateCache(); - LoadStore(); - InitializeRegistry(); - - // The initial, cached policy will be served once the backend is initialized. - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - PolicyBundle expected_bundle; - const PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - expected_bundle.Get(ns).CopyFrom(expected_policy_); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); - std::map<std::string, std::string> contents; - cache_->LoadAllSubkeys("extension-policy", &contents); - ASSERT_EQ(1u, contents.size()); - - // Now sign in. - Connect(2u); - - // Signing out removes all of the component policies from the service and - // from the cache. It does not trigger a refresh. - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - core_.Disconnect(); - store_.policy_.reset(); - store_.NotifyStoreLoaded(); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - const PolicyBundle empty_bundle; - EXPECT_TRUE(service_->policy().Equals(empty_bundle)); - cache_->LoadAllSubkeys("extension-policy", &contents); - ASSERT_EQ(0u, contents.size()); -} - -TEST_F(ComponentCloudPolicyServiceTest, LoadInvalidPolicyFromCache) { - // Put the invalid test policy in the cache. One of its policies will be - // loaded, the other should be filtered out by the schema. - builder_.payload().set_secure_hash(base::SHA1HashString(kInvalidTestPolicy)); - EXPECT_TRUE(cache_->Store( - "extension-policy", kTestExtension, CreateSerializedResponse())); - EXPECT_TRUE(cache_->Store( - "extension-policy-data", kTestExtension, kInvalidTestPolicy)); - - LoadStore(); - InitializeRegistry(); - - // The initial, cached policy will be served once the backend is initialized. - EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&delegate_); - - PolicyBundle expected_bundle; - const PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - expected_bundle.Get(ns).Set("Name", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("published"), - NULL); - EXPECT_TRUE(service_->policy().Equals(expected_bundle)); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_store.cc b/chrome/browser/policy/cloud/component_cloud_policy_store.cc deleted file mode 100644 index 2ddc89b..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_store.cc +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_store.h" - -#include "base/callback.h" -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/sha1.h" -#include "base/strings/string_util.h" -#include "base/values.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_map.h" -#include "url/gurl.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -const char kValue[] = "Value"; -const char kLevel[] = "Level"; -const char kRecommended[] = "Recommended"; - -const struct DomainConstants { - PolicyDomain domain; - const char* proto_cache_key; - const char* data_cache_key; - const char* policy_type; -} kDomains[] = { - { - POLICY_DOMAIN_EXTENSIONS, - "extension-policy", - "extension-policy-data", - dm_protocol::kChromeExtensionPolicyType, - }, -}; - -const DomainConstants* GetDomainConstants(PolicyDomain domain) { - for (size_t i = 0; i < arraysize(kDomains); ++i) { - if (kDomains[i].domain == domain) - return &kDomains[i]; - } - return NULL; -} - -const DomainConstants* GetDomainConstantsForType(const std::string& type) { - for (size_t i = 0; i < arraysize(kDomains); ++i) { - if (kDomains[i].policy_type == type) - return &kDomains[i]; - } - return NULL; -} - -} // namespace - -ComponentCloudPolicyStore::Delegate::~Delegate() {} - -ComponentCloudPolicyStore::ComponentCloudPolicyStore( - Delegate* delegate, - ResourceCache* cache) - : delegate_(delegate), - cache_(cache) { - // Allow the store to be created on a different thread than the thread that - // will end up using it. - DetachFromThread(); -} - -ComponentCloudPolicyStore::~ComponentCloudPolicyStore() { - DCHECK(CalledOnValidThread()); -} - -// static -bool ComponentCloudPolicyStore::SupportsDomain(PolicyDomain domain) { - return GetDomainConstants(domain) != NULL; -} - -// static -bool ComponentCloudPolicyStore::GetPolicyType(PolicyDomain domain, - std::string* policy_type) { - const DomainConstants* constants = GetDomainConstants(domain); - if (constants) - *policy_type = constants->policy_type; - return constants != NULL; -} - -// static -bool ComponentCloudPolicyStore::GetPolicyDomain(const std::string& policy_type, - PolicyDomain* domain) { - const DomainConstants* constants = GetDomainConstantsForType(policy_type); - if (constants) - *domain = constants->domain; - return constants != NULL; -} - -const std::string& ComponentCloudPolicyStore::GetCachedHash( - const PolicyNamespace& ns) const { - DCHECK(CalledOnValidThread()); - std::map<PolicyNamespace, std::string>::const_iterator it = - cached_hashes_.find(ns); - return it == cached_hashes_.end() ? base::EmptyString() : it->second; -} - -void ComponentCloudPolicyStore::SetCredentials(const std::string& username, - const std::string& dm_token) { - DCHECK(CalledOnValidThread()); - DCHECK(username_.empty() || username == username_); - DCHECK(dm_token_.empty() || dm_token == dm_token_); - username_ = username; - dm_token_ = dm_token; -} - -void ComponentCloudPolicyStore::Load() { - DCHECK(CalledOnValidThread()); - typedef std::map<std::string, std::string> ContentMap; - - // Load all cached policy protobufs for each domain. - for (size_t domain = 0; domain < arraysize(kDomains); ++domain) { - const DomainConstants& constants = kDomains[domain]; - ContentMap protos; - cache_->LoadAllSubkeys(constants.proto_cache_key, &protos); - for (ContentMap::iterator it = protos.begin(); it != protos.end(); ++it) { - const std::string& id(it->first); - PolicyNamespace ns(constants.domain, id); - - // Validate each protobuf. - scoped_ptr<em::PolicyFetchResponse> proto(new em::PolicyFetchResponse); - em::ExternalPolicyData payload; - if (!proto->ParseFromString(it->second) || - !ValidateProto( - proto.Pass(), constants.policy_type, id, &payload, NULL)) { - Delete(ns); - continue; - } - - // The protobuf looks good; load the policy data. - std::string data; - PolicyMap policy; - if (cache_->Load(constants.data_cache_key, id, &data) && - ValidateData(data, payload.secure_hash(), &policy)) { - // The data is also good; expose the policies. - policy_bundle_.Get(ns).Swap(&policy); - cached_hashes_[ns] = payload.secure_hash(); - } else { - // The data for this proto couldn't be loaded or is corrupted. - Delete(ns); - } - } - } -} - -bool ComponentCloudPolicyStore::Store(const PolicyNamespace& ns, - const std::string& serialized_policy, - const std::string& secure_hash, - const std::string& data) { - DCHECK(CalledOnValidThread()); - const DomainConstants* constants = GetDomainConstants(ns.domain); - PolicyMap policy; - // |serialized_policy| has already been validated; validate the data now. - if (!constants || !ValidateData(data, secure_hash, &policy)) - return false; - - // Flush the proto and the data to the cache. - cache_->Store(constants->proto_cache_key, ns.component_id, serialized_policy); - cache_->Store(constants->data_cache_key, ns.component_id, data); - // And expose the policy. - policy_bundle_.Get(ns).Swap(&policy); - cached_hashes_[ns] = secure_hash; - delegate_->OnComponentCloudPolicyStoreUpdated(); - return true; -} - -void ComponentCloudPolicyStore::Delete(const PolicyNamespace& ns) { - DCHECK(CalledOnValidThread()); - const DomainConstants* constants = GetDomainConstants(ns.domain); - if (!constants) - return; - - cache_->Delete(constants->proto_cache_key, ns.component_id); - cache_->Delete(constants->data_cache_key, ns.component_id); - - if (!policy_bundle_.Get(ns).empty()) { - policy_bundle_.Get(ns).Clear(); - delegate_->OnComponentCloudPolicyStoreUpdated(); - } -} - -void ComponentCloudPolicyStore::Purge( - PolicyDomain domain, - const ResourceCache::SubkeyFilter& filter) { - DCHECK(CalledOnValidThread()); - const DomainConstants* constants = GetDomainConstants(domain); - if (!constants) - return; - - cache_->FilterSubkeys(constants->proto_cache_key, filter); - cache_->FilterSubkeys(constants->data_cache_key, filter); - - // Stop serving policies for purged namespaces. - bool purged_current_policies = false; - for (PolicyBundle::const_iterator it = policy_bundle_.begin(); - it != policy_bundle_.end(); ++it) { - if (it->first.domain == domain && - filter.Run(it->first.component_id) && - !policy_bundle_.Get(it->first).empty()) { - policy_bundle_.Get(it->first).Clear(); - purged_current_policies = true; - } - } - - // Purge cached hashes, so that those namespaces can be fetched again if the - // policy state changes. - std::map<PolicyNamespace, std::string>::iterator it = cached_hashes_.begin(); - while (it != cached_hashes_.end()) { - if (it->first.domain == domain && filter.Run(it->first.component_id)) { - std::map<PolicyNamespace, std::string>::iterator prev = it; - ++it; - cached_hashes_.erase(prev); - } else { - ++it; - } - } - - if (purged_current_policies) - delegate_->OnComponentCloudPolicyStoreUpdated(); -} - -void ComponentCloudPolicyStore::Clear() { - for (size_t i = 0; i < arraysize(kDomains); ++i) { - cache_->Clear(kDomains[i].proto_cache_key); - cache_->Clear(kDomains[i].data_cache_key); - } - cached_hashes_.clear(); - const PolicyBundle empty_bundle; - if (!policy_bundle_.Equals(empty_bundle)) { - policy_bundle_.Clear(); - delegate_->OnComponentCloudPolicyStoreUpdated(); - } -} - -bool ComponentCloudPolicyStore::ValidatePolicy( - scoped_ptr<em::PolicyFetchResponse> proto, - PolicyNamespace* ns, - em::ExternalPolicyData* payload) { - em::PolicyData policy_data; - if (!ValidateProto( - proto.Pass(), std::string(), std::string(), payload, &policy_data)) { - return false; - } - - if (!policy_data.has_policy_type()) - return false; - - const DomainConstants* constants = - GetDomainConstantsForType(policy_data.policy_type()); - if (!constants || !policy_data.has_settings_entity_id()) - return false; - - ns->domain = constants->domain; - ns->component_id = policy_data.settings_entity_id(); - return true; -} - -bool ComponentCloudPolicyStore::ValidateProto( - scoped_ptr<em::PolicyFetchResponse> proto, - const std::string& policy_type, - const std::string& settings_entity_id, - em::ExternalPolicyData* payload, - em::PolicyData* policy_data) { - if (username_.empty() || dm_token_.empty()) - return false; - - scoped_ptr<ComponentCloudPolicyValidator> validator( - ComponentCloudPolicyValidator::Create( - proto.Pass(), scoped_refptr<base::SequencedTaskRunner>())); - validator->ValidateUsername(username_); - validator->ValidateDMToken(dm_token_, - ComponentCloudPolicyValidator::DM_TOKEN_REQUIRED); - if (!policy_type.empty()) - validator->ValidatePolicyType(policy_type); - if (!settings_entity_id.empty()) - validator->ValidateSettingsEntityId(settings_entity_id); - validator->ValidatePayload(); - // TODO(joaodasilva): validate signature. - validator->RunValidation(); - if (!validator->success()) - return false; - - em::ExternalPolicyData* data = validator->payload().get(); - // The download URL must be empty, or must be a valid URL. - // An empty download URL signals that this component doesn't have cloud - // policy, or that the policy has been removed. - if (data->has_download_url() && !data->download_url().empty()) { - if (!GURL(data->download_url()).is_valid() || - !data->has_secure_hash() || - data->secure_hash().empty()) { - return false; - } - } else if (data->has_secure_hash()) { - return false; - } - - if (payload) - payload->Swap(validator->payload().get()); - if (policy_data) - policy_data->Swap(validator->policy_data().get()); - return true; -} - -bool ComponentCloudPolicyStore::ValidateData( - const std::string& data, - const std::string& secure_hash, - PolicyMap* policy) { - return base::SHA1HashString(data) == secure_hash && ParsePolicy(data, policy); -} - -bool ComponentCloudPolicyStore::ParsePolicy(const std::string& data, - PolicyMap* policy) { - scoped_ptr<base::Value> json(base::JSONReader::Read( - data, base::JSON_PARSE_RFC | base::JSON_DETACHABLE_CHILDREN)); - base::DictionaryValue* dict = NULL; - if (!json || !json->GetAsDictionary(&dict)) - return false; - - // Each top-level key maps a policy name to its description. - // - // Each description is an object that contains the policy value under the - // "Value" key. The optional "Level" key is either "Mandatory" (default) or - // "Recommended". - for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { - base::DictionaryValue* description = NULL; - if (!dict->GetDictionaryWithoutPathExpansion(it.key(), &description)) - return false; - - scoped_ptr<base::Value> value; - if (!description->RemoveWithoutPathExpansion(kValue, &value)) - return false; - - PolicyLevel level = POLICY_LEVEL_MANDATORY; - std::string level_string; - if (description->GetStringWithoutPathExpansion(kLevel, &level_string) && - level_string == kRecommended) { - level = POLICY_LEVEL_RECOMMENDED; - } - - // If policy for components is ever used for device-level settings then - // this must support a configurable scope; assuming POLICY_SCOPE_USER is - // fine for now. - policy->Set(it.key(), level, POLICY_SCOPE_USER, value.release(), NULL); - } - - return true; -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_store.h b/chrome/browser/policy/cloud/component_cloud_policy_store.h deleted file mode 100644 index b6f90da..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_store.h +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_STORE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_STORE_H_ - -#include <map> -#include <string> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/threading/non_thread_safe.h" -#include "chrome/browser/policy/cloud/resource_cache.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_namespace.h" - -namespace enterprise_management { -class ExternalPolicyData; -class PolicyData; -class PolicyFetchResponse; -} - -namespace policy { - -// Validates protobufs for external policy data, validates the data itself, and -// caches both locally. -class ComponentCloudPolicyStore : public base::NonThreadSafe { - public: - class Delegate { - public: - virtual ~Delegate(); - - // Invoked whenever the policies served by policy() have changed, except - // for the initial Load(). - virtual void OnComponentCloudPolicyStoreUpdated() = 0; - }; - - // Both the |delegate| and the |cache| must outlive this object. - ComponentCloudPolicyStore(Delegate* delegate, - ResourceCache* cache); - ~ComponentCloudPolicyStore(); - - // Helper that returns true for PolicyDomains that can be managed by this - // store. - static bool SupportsDomain(PolicyDomain domain); - - // Returns true if |domain| can be managed by this store; in that case, the - // dm_protocol policy type that corresponds to |domain| is stored in - // |policy_type|. Otherwise returns false. - static bool GetPolicyType(PolicyDomain domain, std::string* policy_type); - - // Returns true if |policy_type| corresponds to a policy domain that can be - // managed by this store; in that case, the domain constants is assigned to - // |domain|. Otherwise returns false. - static bool GetPolicyDomain(const std::string& policy_type, - PolicyDomain* domain); - - // The current list of policies. - const PolicyBundle& policy() const { return policy_bundle_; } - - // The cached hash for namespace |ns|, or the empty string if |ns| is not - // cached. - const std::string& GetCachedHash(const PolicyNamespace& ns) const; - - // |username| and |dm_token| are used to validate the cached data, and data - // stored later. - // All ValidatePolicy() requests without credentials fail. - void SetCredentials(const std::string& username, - const std::string& dm_token); - - // Loads and validates all the currently cached protobufs and policy data. - // This is performed synchronously, and policy() will return the cached - // policies after this call. - void Load(); - - // Stores the protobuf and |data| for namespace |ns|. The protobuf is passed - // serialized in |serialized_policy_proto|, and must have been validated - // before. - // The |data| is validated during this call, and its secure hash must match - // |secure_hash|. - // Returns false if |data| failed validation, otherwise returns true and the - // data was stored in the cache. - bool Store(const PolicyNamespace& ns, - const std::string& serialized_policy_proto, - const std::string& secure_hash, - const std::string& data); - - // Deletes the storage of namespace |ns| and stops serving its policies. - void Delete(const PolicyNamespace& ns); - - // Deletes the storage of all components of |domain| that pass then given - // |filter|, and stops serving their policies. - void Purge(PolicyDomain domain, - const ResourceCache::SubkeyFilter& filter); - - // Deletes the storage of every component. - void Clear(); - - // Validates |proto| and returns the corresponding policy namespace in |ns|, - // and the parsed ExternalPolicyData in |payload|. - // If |proto| validates successfully then its |payload| can be trusted, and - // the data referenced there can be downloaded. A |proto| must be validated - // before attempting to download the data, and before storing both. - bool ValidatePolicy( - scoped_ptr<enterprise_management::PolicyFetchResponse> proto, - PolicyNamespace* ns, - enterprise_management::ExternalPolicyData* payload); - - private: - // Helper for ValidatePolicy(), that's also used to validate protobufs - // loaded from the disk cache. - bool ValidateProto( - scoped_ptr<enterprise_management::PolicyFetchResponse> proto, - const std::string& policy_type, - const std::string& settings_entity_id, - enterprise_management::ExternalPolicyData* payload, - enterprise_management::PolicyData* policy_data); - - // Validates the JSON policy serialized in |data|, and verifies its hash - // with |secure_hash|. Returns true on success, and in that case stores the - // parsed policies in |policy|. - bool ValidateData(const std::string& data, - const std::string& secure_hash, - PolicyMap* policy); - - // Parses the JSON policy in |data| into |policy|, and returns true if the - // parse was successful. - bool ParsePolicy(const std::string& data, PolicyMap* policy); - - Delegate* delegate_; - ResourceCache* cache_; - std::string username_; - std::string dm_token_; - - PolicyBundle policy_bundle_; - std::map<PolicyNamespace, std::string> cached_hashes_; - - DISALLOW_COPY_AND_ASSIGN(ComponentCloudPolicyStore); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_STORE_H_ diff --git a/chrome/browser/policy/cloud/component_cloud_policy_store_unittest.cc b/chrome/browser/policy/cloud/component_cloud_policy_store_unittest.cc deleted file mode 100644 index aed849b..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_store_unittest.cc +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_store.h" - -#include <map> -#include <string> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/callback.h" -#include "base/files/scoped_temp_dir.h" -#include "base/memory/ref_counted.h" -#include "base/sha1.h" -#include "base/test/test_simple_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "chrome/browser/policy/cloud/resource_cache.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace em = enterprise_management; - -using testing::Mock; - -namespace policy { - -namespace { - -const char kTestExtension[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; -const char kTestDownload[] = "http://example.com/getpolicy?id=123"; -const char kTestPolicy[] = - "{" - " \"Name\": {" - " \"Value\": \"disabled\"" - " }," - " \"Second\": {" - " \"Value\": \"maybe\"," - " \"Level\": \"Recommended\"" - " }" - "}"; - -std::string TestPolicyHash() { - return base::SHA1HashString(kTestPolicy); -} - -bool NotEqual(const std::string& expected, const std::string& key) { - return key != expected; -} - -bool True(const std::string& ignored) { - return true; -} - -class MockComponentCloudPolicyStoreDelegate - : public ComponentCloudPolicyStore::Delegate { - public: - virtual ~MockComponentCloudPolicyStoreDelegate() {} - - MOCK_METHOD0(OnComponentCloudPolicyStoreUpdated, void()); -}; - -} // namespace - -class ComponentCloudPolicyStoreTest : public testing::Test { - protected: - virtual void SetUp() OVERRIDE { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - cache_.reset(new ResourceCache( - temp_dir_.path(), - make_scoped_refptr(new base::TestSimpleTaskRunner))); - store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::kFakeUsername, - ComponentPolicyBuilder::kFakeToken); - - builder_.policy_data().set_policy_type( - dm_protocol::kChromeExtensionPolicyType); - builder_.policy_data().set_settings_entity_id(kTestExtension); - builder_.payload().set_download_url(kTestDownload); - builder_.payload().set_secure_hash(TestPolicyHash()); - - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - PolicyMap& policy = expected_bundle_.Get(ns); - policy.Set("Name", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("disabled"), NULL); - policy.Set("Second", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - base::Value::CreateStringValue("maybe"), NULL); - } - - // Returns true if the policy exposed by the |store_| is empty. - bool IsEmpty() { - return store_->policy().begin() == store_->policy().end(); - } - - scoped_ptr<em::PolicyFetchResponse> CreateResponse() { - builder_.Build(); - return make_scoped_ptr(new em::PolicyFetchResponse(builder_.policy())); - } - - std::string CreateSerializedResponse() { - builder_.Build(); - return builder_.GetBlob(); - } - - base::ScopedTempDir temp_dir_; - scoped_ptr<ResourceCache> cache_; - scoped_ptr<ComponentCloudPolicyStore> store_; - MockComponentCloudPolicyStoreDelegate store_delegate_; - ComponentPolicyBuilder builder_; - PolicyBundle expected_bundle_; -}; - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicy) { - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_TRUE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); - EXPECT_EQ(POLICY_DOMAIN_EXTENSIONS, ns.domain); - EXPECT_EQ(kTestExtension, ns.component_id); - EXPECT_EQ(kTestDownload, payload.download_url()); - EXPECT_EQ(TestPolicyHash(), payload.secure_hash()); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyWrongUsername) { - builder_.policy_data().set_username("anotheruser@example.com"); - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_FALSE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyWrongDMToken) { - builder_.policy_data().set_request_token("notmytoken"); - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_FALSE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyBadType) { - builder_.policy_data().set_policy_type(dm_protocol::kChromeUserPolicyType); - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_FALSE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyBadDownloadUrl) { - builder_.payload().set_download_url("invalidurl"); - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_FALSE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyEmptyDownloadUrl) { - builder_.payload().clear_download_url(); - builder_.payload().clear_secure_hash(); - em::ExternalPolicyData payload; - PolicyNamespace ns; - // This is valid; it's how "no policy" is signalled to the client. - EXPECT_TRUE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidatePolicyBadPayload) { - builder_.clear_payload(); - builder_.policy_data().set_policy_value("broken"); - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_FALSE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidateNoCredentials) { - store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - em::ExternalPolicyData payload; - PolicyNamespace ns; - EXPECT_FALSE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); -} - -TEST_F(ComponentCloudPolicyStoreTest, ValidateWrongCredentials) { - em::ExternalPolicyData payload; - PolicyNamespace ns; - // Verify that the default response validates with the right credentials. - EXPECT_TRUE(store_->ValidatePolicy(CreateResponse(), &ns, &payload)); - // Now store that response. - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - EXPECT_TRUE(store_->Store( - ns, CreateSerializedResponse(), TestPolicyHash(), kTestPolicy)); - Mock::VerifyAndClearExpectations(&store_delegate_); - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); - // And verify that the response data in the cache. - std::map<std::string, std::string> contents; - cache_->LoadAllSubkeys("extension-policy", &contents); - EXPECT_FALSE(contents.empty()); - - // Try loading the cached response data with wrong credentials. - ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - another_store.SetCredentials("wrongdude@example.com", "wrongtoken"); - another_store.Load(); - const PolicyBundle empty_bundle; - EXPECT_TRUE(another_store.policy().Equals(empty_bundle)); - - // The failure to read wiped the cache. - cache_->LoadAllSubkeys("extension-policy", &contents); - EXPECT_TRUE(contents.empty()); -} - -TEST_F(ComponentCloudPolicyStoreTest, StoreAndLoad) { - // Initially empty. - EXPECT_TRUE(IsEmpty()); - store_->Load(); - EXPECT_TRUE(IsEmpty()); - - // Store policy for an unsupported domain. - PolicyNamespace ns(POLICY_DOMAIN_CHROME, kTestExtension); - builder_.policy_data().set_policy_type(dm_protocol::kChromeUserPolicyType); - EXPECT_FALSE(store_->Store( - ns, CreateSerializedResponse(), TestPolicyHash(), kTestPolicy)); - - // Store policy with the wrong hash. - builder_.policy_data().set_policy_type( - dm_protocol::kChromeExtensionPolicyType); - ns.domain = POLICY_DOMAIN_EXTENSIONS; - builder_.payload().set_secure_hash("badash"); - EXPECT_FALSE(store_->Store( - ns, CreateSerializedResponse(), "badash", kTestPolicy)); - - // Store policy without a hash. - builder_.payload().clear_secure_hash(); - EXPECT_FALSE(store_->Store( - ns, CreateSerializedResponse(), std::string(), kTestPolicy)); - - // Store policy with invalid JSON data. - static const char kInvalidData[] = "{ not json }"; - const std::string invalid_data_hash = base::SHA1HashString(kInvalidData); - builder_.payload().set_secure_hash(invalid_data_hash); - EXPECT_FALSE(store_->Store( - ns, CreateSerializedResponse(), invalid_data_hash, kInvalidData)); - - // All of those failed. - EXPECT_TRUE(IsEmpty()); - EXPECT_EQ(std::string(), store_->GetCachedHash(ns)); - - // Now store a valid policy. - builder_.payload().set_secure_hash(TestPolicyHash()); - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - EXPECT_TRUE(store_->Store( - ns, CreateSerializedResponse(), TestPolicyHash(), kTestPolicy)); - Mock::VerifyAndClearExpectations(&store_delegate_); - EXPECT_FALSE(IsEmpty()); - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); - EXPECT_EQ(TestPolicyHash(), store_->GetCachedHash(ns)); - - // Loading from the cache validates the policy data again. - ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - another_store.SetCredentials(ComponentPolicyBuilder::kFakeUsername, - ComponentPolicyBuilder::kFakeToken); - another_store.Load(); - EXPECT_TRUE(another_store.policy().Equals(expected_bundle_)); - EXPECT_EQ(TestPolicyHash(), another_store.GetCachedHash(ns)); -} - -TEST_F(ComponentCloudPolicyStoreTest, Updates) { - // Store some policies. - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - EXPECT_TRUE(store_->Store( - ns, CreateSerializedResponse(), TestPolicyHash(), kTestPolicy)); - Mock::VerifyAndClearExpectations(&store_delegate_); - EXPECT_FALSE(IsEmpty()); - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); - - // Deleting a non-existant namespace doesn't trigger updates. - PolicyNamespace ns_fake(POLICY_DOMAIN_EXTENSIONS, "nosuchid"); - store_->Delete(ns_fake); - Mock::VerifyAndClearExpectations(&store_delegate_); - - // Deleting a namespace that has policies triggers an update. - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - store_->Delete(ns); - Mock::VerifyAndClearExpectations(&store_delegate_); -} - -TEST_F(ComponentCloudPolicyStoreTest, Purge) { - // Store a valid policy. - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - EXPECT_TRUE(store_->Store( - ns, CreateSerializedResponse(), TestPolicyHash(), kTestPolicy)); - Mock::VerifyAndClearExpectations(&store_delegate_); - EXPECT_FALSE(IsEmpty()); - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); - - // Purge other components. - store_->Purge(POLICY_DOMAIN_EXTENSIONS, - base::Bind(&NotEqual, kTestExtension)); - - // The policy for |ns| is still served. - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); - - // Loading the store again will still see |ns|. - ComponentCloudPolicyStore another_store(&store_delegate_, cache_.get()); - const PolicyBundle empty_bundle; - EXPECT_TRUE(another_store.policy().Equals(empty_bundle)); - another_store.SetCredentials(ComponentPolicyBuilder::kFakeUsername, - ComponentPolicyBuilder::kFakeToken); - another_store.Load(); - EXPECT_TRUE(another_store.policy().Equals(expected_bundle_)); - - // Now purge everything. - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - store_->Purge(POLICY_DOMAIN_EXTENSIONS, base::Bind(&True)); - Mock::VerifyAndClearExpectations(&store_delegate_); - - // No policies are served anymore. - EXPECT_TRUE(store_->policy().Equals(empty_bundle)); - - // And they aren't loaded anymore either. - ComponentCloudPolicyStore yet_another_store(&store_delegate_, cache_.get()); - yet_another_store.SetCredentials(ComponentPolicyBuilder::kFakeUsername, - ComponentPolicyBuilder::kFakeToken); - yet_another_store.Load(); - EXPECT_TRUE(yet_another_store.policy().Equals(empty_bundle)); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_updater.cc b/chrome/browser/policy/cloud/component_cloud_policy_updater.cc deleted file mode 100644 index 43cfb27..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_updater.cc +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_updater.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/logging.h" -#include "base/sequenced_task_runner.h" -#include "base/strings/string_number_conversions.h" -#include "chrome/browser/policy/cloud/component_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -// The maximum size of the serialized policy protobuf. -const size_t kPolicyProtoMaxSize = 16 * 1024; - -// The maximum size of the downloaded policy data. -const int64 kPolicyDataMaxSize = 5 * 1024 * 1024; - -// Tha maximum number of policy data fetches to run in parallel. -const int64 kMaxParallelPolicyDataFetches = 2; - -} // namespace - -ComponentCloudPolicyUpdater::ComponentCloudPolicyUpdater( - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher, - ComponentCloudPolicyStore* store) - : store_(store), - external_policy_data_updater_(task_runner, - external_policy_data_fetcher.Pass(), - kMaxParallelPolicyDataFetches) { -} - -ComponentCloudPolicyUpdater::~ComponentCloudPolicyUpdater() { -} - -void ComponentCloudPolicyUpdater::UpdateExternalPolicy( - scoped_ptr<em::PolicyFetchResponse> response) { - // Keep a serialized copy of |response|, to cache it later. - // The policy is also rejected if it exceeds the maximum size. - std::string serialized_response; - if (!response->SerializeToString(&serialized_response) || - serialized_response.size() > kPolicyProtoMaxSize) { - return; - } - - // Validate the policy before doing anything else. - PolicyNamespace ns; - em::ExternalPolicyData data; - if (!store_->ValidatePolicy(response.Pass(), &ns, &data)) { - LOG(ERROR) << "Failed to validate component policy fetched from DMServer"; - return; - } - - // Maybe the data for this hash has already been downloaded and cached. - const std::string& cached_hash = store_->GetCachedHash(ns); - if (!cached_hash.empty() && data.secure_hash() == cached_hash) - return; - - // TODO(joaodasilva): implement the other two auth methods. - if (data.download_auth_method() != em::ExternalPolicyData::NONE) - return; - - const std::string key = NamespaceToKey(ns); - - if (data.download_url().empty() || !data.has_secure_hash()) { - // If there is no policy for this component or the policy has been removed, - // cancel any existing request to fetch policy for this component. - external_policy_data_updater_.CancelExternalDataFetch(key); - - // Delete any existing policy for this component. - store_->Delete(ns); - } else { - // Make a request to fetch policy for this component. If another fetch - // request is already pending for the component, it will be canceled. - external_policy_data_updater_.FetchExternalData( - key, - ExternalPolicyDataUpdater::Request(data.download_url(), - data.secure_hash(), - kPolicyDataMaxSize), - base::Bind(&ComponentCloudPolicyStore::Store, base::Unretained(store_), - ns, - serialized_response, - data.secure_hash())); - } -} - -void ComponentCloudPolicyUpdater::CancelUpdate(const PolicyNamespace& ns) { - external_policy_data_updater_.CancelExternalDataFetch(NamespaceToKey(ns)); -} - -std::string ComponentCloudPolicyUpdater::NamespaceToKey( - const PolicyNamespace& ns) { - const std::string domain = base::IntToString(ns.domain); - const std::string size = base::IntToString(domain.size()); - return size + ":" + domain + ":" + ns.component_id; -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/component_cloud_policy_updater.h b/chrome/browser/policy/cloud/component_cloud_policy_updater.h deleted file mode 100644 index f711607..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_updater.h +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_UPDATER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_UPDATER_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/cloud/external_policy_data_updater.h" -#include "components/policy/core/common/policy_namespace.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace enterprise_management { -class PolicyFetchResponse; -} - -namespace policy { - -class ComponentCloudPolicyStore; -class ExternalPolicyDataFetcher; - -// This class downloads external policy data, given PolicyFetchResponses. -// It validates the PolicyFetchResponse and its corresponding data, and caches -// them in a ComponentCloudPolicyStore. It also enforces size limits on what's -// cached. -// It retries to download the policy data periodically when a download fails. -class ComponentCloudPolicyUpdater { - public: - // This class runs on the background thread represented by |task_runner|, - // which must support file I/O. All network I/O is delegated to the - // |external_policy_data_fetcher|. - ComponentCloudPolicyUpdater( - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher, - ComponentCloudPolicyStore* store); - ~ComponentCloudPolicyUpdater(); - - // |response| is the latest policy information fetched for some component. - // This method schedules the download of the policy data, if |response| is - // validated. If the downloaded data also passes validation then that data - // will be passed to the |store_|. - void UpdateExternalPolicy( - scoped_ptr<enterprise_management::PolicyFetchResponse> response); - - // Cancels any pending operations for the given namespace. - void CancelUpdate(const PolicyNamespace& ns); - - private: - std::string NamespaceToKey(const PolicyNamespace& ns); - - ComponentCloudPolicyStore* store_; - ExternalPolicyDataUpdater external_policy_data_updater_; - - DISALLOW_COPY_AND_ASSIGN(ComponentCloudPolicyUpdater); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_COMPONENT_CLOUD_POLICY_UPDATER_H_ diff --git a/chrome/browser/policy/cloud/component_cloud_policy_updater_unittest.cc b/chrome/browser/policy/cloud/component_cloud_policy_updater_unittest.cc deleted file mode 100644 index f5ca82b..0000000 --- a/chrome/browser/policy/cloud/component_cloud_policy_updater_unittest.cc +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/component_cloud_policy_updater.h" - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/files/scoped_temp_dir.h" -#include "base/sequenced_task_runner.h" -#include "base/sha1.h" -#include "base/test/test_simple_task_runner.h" -#include "base/values.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/component_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" -#include "chrome/browser/policy/cloud/policy_builder.h" -#include "chrome/browser/policy/cloud/resource_cache.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_types.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_context_getter.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace em = enterprise_management; - -using testing::Mock; - -namespace policy { - -namespace { - -const char kTestExtension[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; -const char kTestExtension2[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; -const char kTestExtension3[] = "cccccccccccccccccccccccccccccccc"; -const char kTestDownload[] = "http://example.com/getpolicy?id=123"; -const char kTestDownload2[] = "http://example.com/getpolicy?id=456"; -const char kTestDownload3[] = "http://example.com/getpolicy?id=789"; -const char kTestPolicy[] = - "{" - " \"Name\": {" - " \"Value\": \"disabled\"" - " }," - " \"Second\": {" - " \"Value\": \"maybe\"," - " \"Level\": \"Recommended\"" - " }" - "}"; - -class MockComponentCloudPolicyStoreDelegate - : public ComponentCloudPolicyStore::Delegate { - public: - virtual ~MockComponentCloudPolicyStoreDelegate() {} - - MOCK_METHOD0(OnComponentCloudPolicyStoreUpdated, void()); -}; - -} // namespace - -class ComponentCloudPolicyUpdaterTest : public testing::Test { - protected: - virtual void SetUp() OVERRIDE; - virtual void TearDown() OVERRIDE; - - scoped_ptr<em::PolicyFetchResponse> CreateResponse(); - - scoped_refptr<base::TestSimpleTaskRunner> task_runner_; - base::ScopedTempDir temp_dir_; - scoped_ptr<ResourceCache> cache_; - scoped_ptr<ComponentCloudPolicyStore> store_; - MockComponentCloudPolicyStoreDelegate store_delegate_; - net::TestURLFetcherFactory fetcher_factory_; - scoped_ptr<ExternalPolicyDataFetcherBackend> fetcher_backend_; - scoped_ptr<ComponentCloudPolicyUpdater> updater_; - ComponentPolicyBuilder builder_; - PolicyBundle expected_bundle_; -}; - -void ComponentCloudPolicyUpdaterTest::SetUp() { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - task_runner_ = new base::TestSimpleTaskRunner(); - cache_.reset(new ResourceCache(temp_dir_.path(), task_runner_)); - store_.reset(new ComponentCloudPolicyStore(&store_delegate_, cache_.get())); - store_->SetCredentials(ComponentPolicyBuilder::kFakeUsername, - ComponentPolicyBuilder::kFakeToken); - fetcher_factory_.set_remove_fetcher_on_delete(true); - fetcher_backend_.reset(new ExternalPolicyDataFetcherBackend( - task_runner_, - scoped_refptr<net::URLRequestContextGetter>())); - updater_.reset(new ComponentCloudPolicyUpdater( - task_runner_, - fetcher_backend_->CreateFrontend(task_runner_), - store_.get())); - ASSERT_EQ(store_->policy().end(), store_->policy().begin()); - - builder_.policy_data().set_policy_type( - dm_protocol::kChromeExtensionPolicyType); - builder_.policy_data().set_settings_entity_id(kTestExtension); - builder_.payload().set_download_url(kTestDownload); - builder_.payload().set_secure_hash(base::SHA1HashString(kTestPolicy)); - - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - PolicyMap& policy = expected_bundle_.Get(ns); - policy.Set("Name", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("disabled"), NULL); - policy.Set("Second", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - base::Value::CreateStringValue("maybe"), NULL); -} - -void ComponentCloudPolicyUpdaterTest::TearDown() { - updater_.reset(); - task_runner_->RunUntilIdle(); -} - -scoped_ptr<em::PolicyFetchResponse> - ComponentCloudPolicyUpdaterTest::CreateResponse() { - builder_.Build(); - return make_scoped_ptr(new em::PolicyFetchResponse(builder_.policy())); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, FetchAndCache) { - // Submit a policy fetch response. - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that a download has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL()); - - // Complete the download. - fetcher->set_response_code(200); - fetcher->SetResponseString(kTestPolicy); - fetcher->delegate()->OnURLFetchComplete(fetcher); - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - task_runner_->RunUntilIdle(); - Mock::VerifyAndClearExpectations(&store_delegate_); - - // Verify that the downloaded policy is being served. - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, PolicyFetchResponseTooLarge) { - // Submit a policy fetch response that exceeds the allowed maximum size. - std::string long_download("http://example.com/get?id="); - long_download.append(20 * 1024, '1'); - builder_.payload().set_download_url(long_download); - updater_->UpdateExternalPolicy(CreateResponse()); - - // Submit two valid policy fetch responses. - builder_.policy_data().set_settings_entity_id(kTestExtension2); - builder_.payload().set_download_url(kTestDownload2); - updater_->UpdateExternalPolicy(CreateResponse()); - builder_.policy_data().set_settings_entity_id(kTestExtension3); - builder_.payload().set_download_url(kTestDownload3); - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the first policy fetch response has been ignored and downloads - // have been started for the next two fetch responses instead. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload2), fetcher->GetOriginalURL()); - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload3), fetcher->GetOriginalURL()); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, PolicyFetchResponseInvalid) { - // Submit an invalid policy fetch response. - builder_.policy_data().set_username("wronguser@example.com"); - updater_->UpdateExternalPolicy(CreateResponse()); - - // Submit two valid policy fetch responses. - builder_.policy_data().set_username(ComponentPolicyBuilder::kFakeUsername); - builder_.policy_data().set_settings_entity_id(kTestExtension2); - builder_.payload().set_download_url(kTestDownload2); - updater_->UpdateExternalPolicy(CreateResponse()); - builder_.policy_data().set_settings_entity_id(kTestExtension3); - builder_.payload().set_download_url(kTestDownload3); - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the first policy fetch response has been ignored and downloads - // have been started for the next two fetch responses instead. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload2), fetcher->GetOriginalURL()); - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload3), fetcher->GetOriginalURL()); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, AlreadyCached) { - // Cache policy for an extension. - builder_.Build(); - PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension); - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - EXPECT_TRUE(store_->Store(ns, - builder_.GetBlob(), - base::SHA1HashString(kTestPolicy), - kTestPolicy)); - Mock::VerifyAndClearExpectations(&store_delegate_); - - // Submit a policy fetch response whose extension ID and hash match the - // already cached policy. - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that no download has been started. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, PolicyDataInvalid) { - // Submit three policy fetch responses. - updater_->UpdateExternalPolicy(CreateResponse()); - builder_.payload().set_download_url(kTestDownload2); - builder_.policy_data().set_settings_entity_id(kTestExtension2); - updater_->UpdateExternalPolicy(CreateResponse()); - builder_.policy_data().set_settings_entity_id(kTestExtension3); - builder_.payload().set_download_url(kTestDownload3); - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the first download has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL()); - - // Verify that the second download has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload2), fetcher->GetOriginalURL()); - - // Indicate that the policy data size will exceed allowed maximum. - fetcher->delegate()->OnURLFetchDownloadProgress(fetcher, 6 * 1024 * 1024, -1); - task_runner_->RunUntilIdle(); - - // Verify that the third download has been started. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload3), fetcher->GetOriginalURL()); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, FetchUpdatedData) { - // Submit a policy fetch response. - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the first download has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL()); - - // Submit a second policy fetch response for the same extension with an - // updated download URL. - builder_.payload().set_download_url(kTestDownload2); - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the first download is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second download has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload2), fetcher->GetOriginalURL()); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, FetchUpdatedDataWithoutPolicy) { - // Submit a policy fetch response. - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the download has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL()); - - // Complete the download. - fetcher->set_response_code(200); - fetcher->SetResponseString(kTestPolicy); - fetcher->delegate()->OnURLFetchComplete(fetcher); - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - task_runner_->RunUntilIdle(); - Mock::VerifyAndClearExpectations(&store_delegate_); - - // Verify that the downloaded policy is being served. - EXPECT_TRUE(store_->policy().Equals(expected_bundle_)); - - // Submit a second policy fetch response for the same extension with no - // download URL, meaning that no policy should be provided for this extension. - builder_.payload().clear_download_url(); - builder_.payload().clear_secure_hash(); - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()); - updater_->UpdateExternalPolicy(CreateResponse()); - Mock::VerifyAndClearExpectations(&store_delegate_); - task_runner_->RunUntilIdle(); - - // Verify that no download has been started. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the policy is no longer being served. - const PolicyBundle empty_bundle; - EXPECT_TRUE(store_->policy().Equals(empty_bundle)); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, NoPolicy) { - // Submit a policy fetch response with a valid download URL. - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the download has been started. - EXPECT_TRUE(fetcher_factory_.GetFetcherByID(0)); - - // Update the policy fetch response before the download has finished. The new - // policy fetch response has no download URL. - builder_.payload().Clear(); - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the download is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); -} - -TEST_F(ComponentCloudPolicyUpdaterTest, CancelUpdate) { - // Submit a policy fetch response with a valid download URL. - updater_->UpdateExternalPolicy(CreateResponse()); - task_runner_->RunUntilIdle(); - - // Verify that the download has been started. - EXPECT_TRUE(fetcher_factory_.GetFetcherByID(0)); - - // Now cancel that update before the download completes. - EXPECT_CALL(store_delegate_, OnComponentCloudPolicyStoreUpdated()).Times(0); - updater_->CancelUpdate( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kTestExtension)); - task_runner_->RunUntilIdle(); - Mock::VerifyAndClearExpectations(&store_delegate_); - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/device_management_service.cc b/chrome/browser/policy/cloud/device_management_service.cc deleted file mode 100644 index 51b3a904..0000000 --- a/chrome/browser/policy/cloud/device_management_service.cc +++ /dev/null @@ -1,515 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/device_management_service.h" - -#include <utility> - -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" -#include "base/message_loop/message_loop_proxy.h" -#include "net/base/escape.h" -#include "net/base/load_flags.h" -#include "net/base/net_errors.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_status.h" -#include "url/gurl.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -const char kPostContentType[] = "application/protobuf"; - -const char kServiceTokenAuthHeader[] = "Authorization: GoogleLogin auth="; -const char kDMTokenAuthHeader[] = "Authorization: GoogleDMToken token="; - -// Number of times to retry on ERR_NETWORK_CHANGED errors. -const int kMaxNetworkChangedRetries = 3; - -// HTTP Error Codes of the DM Server with their concrete meanings in the context -// of the DM Server communication. -const int kSuccess = 200; -const int kInvalidArgument = 400; -const int kInvalidAuthCookieOrDMToken = 401; -const int kMissingLicenses = 402; -const int kDeviceManagementNotAllowed = 403; -const int kInvalidURL = 404; // This error is not coming from the GFE. -const int kInvalidSerialNumber = 405; -const int kDeviceIdConflict = 409; -const int kDeviceNotFound = 410; -const int kPendingApproval = 412; -const int kInternalServerError = 500; -const int kServiceUnavailable = 503; -const int kPolicyNotFound = 902; // This error is not sent as HTTP status code. - -bool IsProxyError(const net::URLRequestStatus status) { - switch (status.error()) { - case net::ERR_PROXY_CONNECTION_FAILED: - case net::ERR_TUNNEL_CONNECTION_FAILED: - case net::ERR_PROXY_AUTH_UNSUPPORTED: - case net::ERR_HTTPS_PROXY_TUNNEL_RESPONSE: - case net::ERR_MANDATORY_PROXY_CONFIGURATION_FAILED: - case net::ERR_PROXY_CERTIFICATE_INVALID: - case net::ERR_SOCKS_CONNECTION_FAILED: - case net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE: - return true; - } - return false; -} - -bool IsProtobufMimeType(const net::URLFetcher* fetcher) { - return fetcher->GetResponseHeaders()->HasHeaderValue( - "content-type", "application/x-protobuffer"); -} - -bool FailedWithProxy(const net::URLFetcher* fetcher) { - if ((fetcher->GetLoadFlags() & net::LOAD_BYPASS_PROXY) != 0) { - // The request didn't use a proxy. - return false; - } - - if (!fetcher->GetStatus().is_success() && - IsProxyError(fetcher->GetStatus())) { - LOG(WARNING) << "Proxy failed while contacting dmserver."; - return true; - } - - if (fetcher->GetStatus().is_success() && - fetcher->GetResponseCode() == kSuccess && - fetcher->WasFetchedViaProxy() && - !IsProtobufMimeType(fetcher)) { - // The proxy server can be misconfigured but pointing to an existing - // server that replies to requests. Try to recover if a successful - // request that went through a proxy returns an unexpected mime type. - LOG(WARNING) << "Got bad mime-type in response from dmserver that was " - << "fetched via a proxy."; - return true; - } - - return false; -} - -const char* UserAffiliationToString(UserAffiliation affiliation) { - switch (affiliation) { - case USER_AFFILIATION_MANAGED: - return dm_protocol::kValueUserAffiliationManaged; - case USER_AFFILIATION_NONE: - return dm_protocol::kValueUserAffiliationNone; - } - NOTREACHED() << "Invalid user affiliation " << affiliation; - return dm_protocol::kValueUserAffiliationNone; -} - -const char* JobTypeToRequestType(DeviceManagementRequestJob::JobType type) { - switch (type) { - case DeviceManagementRequestJob::TYPE_AUTO_ENROLLMENT: - return dm_protocol::kValueRequestAutoEnrollment; - case DeviceManagementRequestJob::TYPE_REGISTRATION: - return dm_protocol::kValueRequestRegister; - case DeviceManagementRequestJob::TYPE_POLICY_FETCH: - return dm_protocol::kValueRequestPolicy; - case DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH: - return dm_protocol::kValueRequestApiAuthorization; - case DeviceManagementRequestJob::TYPE_UNREGISTRATION: - return dm_protocol::kValueRequestUnregister; - case DeviceManagementRequestJob::TYPE_UPLOAD_CERTIFICATE: - return dm_protocol::kValueRequestUploadCertificate; - } - NOTREACHED() << "Invalid job type " << type; - return ""; -} - -} // namespace - -// Request job implementation used with DeviceManagementService. -class DeviceManagementRequestJobImpl : public DeviceManagementRequestJob { - public: - DeviceManagementRequestJobImpl( - JobType type, - const std::string& agent_parameter, - const std::string& platform_parameter, - DeviceManagementService* service, - net::URLRequestContextGetter* request_context); - virtual ~DeviceManagementRequestJobImpl(); - - // Handles the URL request response. - void HandleResponse(const net::URLRequestStatus& status, - int response_code, - const net::ResponseCookies& cookies, - const std::string& data); - - // Gets the URL to contact. - GURL GetURL(const std::string& server_url); - - // Configures the fetcher, setting up payload and headers. - void ConfigureRequest(net::URLFetcher* fetcher); - - // Returns true if this job should be retried. |fetcher| has just completed, - // and can be inspected to determine if the request failed and should be - // retried. - bool ShouldRetry(const net::URLFetcher* fetcher); - - // Invoked right before retrying this job. - void PrepareRetry(); - - protected: - // DeviceManagementRequestJob: - virtual void Run() OVERRIDE; - - private: - // Invokes the callback with the given error code. - void ReportError(DeviceManagementStatus code); - - // Pointer to the service this job is associated with. - DeviceManagementService* service_; - - // Whether the BYPASS_PROXY flag should be set by ConfigureRequest(). - bool bypass_proxy_; - - // Number of times that this job has been retried due to ERR_NETWORK_CHANGED. - int retries_count_; - - // The request context to use for this job. - net::URLRequestContextGetter* request_context_; - - DISALLOW_COPY_AND_ASSIGN(DeviceManagementRequestJobImpl); -}; - -DeviceManagementRequestJobImpl::DeviceManagementRequestJobImpl( - JobType type, - const std::string& agent_parameter, - const std::string& platform_parameter, - DeviceManagementService* service, - net::URLRequestContextGetter* request_context) - : DeviceManagementRequestJob(type, agent_parameter, platform_parameter), - service_(service), - bypass_proxy_(false), - retries_count_(0), - request_context_(request_context) {} - -DeviceManagementRequestJobImpl::~DeviceManagementRequestJobImpl() { - service_->RemoveJob(this); -} - -void DeviceManagementRequestJobImpl::Run() { - service_->AddJob(this); -} - -void DeviceManagementRequestJobImpl::HandleResponse( - const net::URLRequestStatus& status, - int response_code, - const net::ResponseCookies& cookies, - const std::string& data) { - if (status.status() != net::URLRequestStatus::SUCCESS) { - LOG(WARNING) << "DMServer request failed, status: " << status.status() - << ", error: " << status.error(); - em::DeviceManagementResponse dummy_response; - callback_.Run(DM_STATUS_REQUEST_FAILED, status.error(), dummy_response); - return; - } - - if (response_code != kSuccess) - LOG(WARNING) << "DMServer sent an error response: " << response_code; - - switch (response_code) { - case kSuccess: { - em::DeviceManagementResponse response; - if (!response.ParseFromString(data)) { - ReportError(DM_STATUS_RESPONSE_DECODING_ERROR); - return; - } - callback_.Run(DM_STATUS_SUCCESS, net::OK, response); - return; - } - case kInvalidArgument: - ReportError(DM_STATUS_REQUEST_INVALID); - return; - case kInvalidAuthCookieOrDMToken: - ReportError(DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID); - return; - case kMissingLicenses: - ReportError(DM_STATUS_SERVICE_MISSING_LICENSES); - return; - case kDeviceManagementNotAllowed: - ReportError(DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED); - return; - case kPendingApproval: - ReportError(DM_STATUS_SERVICE_ACTIVATION_PENDING); - return; - case kInvalidURL: - case kInternalServerError: - case kServiceUnavailable: - ReportError(DM_STATUS_TEMPORARY_UNAVAILABLE); - return; - case kDeviceNotFound: - ReportError(DM_STATUS_SERVICE_DEVICE_NOT_FOUND); - return; - case kPolicyNotFound: - ReportError(DM_STATUS_SERVICE_POLICY_NOT_FOUND); - return; - case kInvalidSerialNumber: - ReportError(DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER); - return; - case kDeviceIdConflict: - ReportError(DM_STATUS_SERVICE_DEVICE_ID_CONFLICT); - return; - default: - // Handle all unknown 5xx HTTP error codes as temporary and any other - // unknown error as one that needs more time to recover. - if (response_code >= 500 && response_code <= 599) - ReportError(DM_STATUS_TEMPORARY_UNAVAILABLE); - else - ReportError(DM_STATUS_HTTP_STATUS_ERROR); - return; - } -} - -GURL DeviceManagementRequestJobImpl::GetURL( - const std::string& server_url) { - std::string result(server_url); - result += '?'; - for (ParameterMap::const_iterator entry(query_params_.begin()); - entry != query_params_.end(); - ++entry) { - if (entry != query_params_.begin()) - result += '&'; - result += net::EscapeQueryParamValue(entry->first, true); - result += '='; - result += net::EscapeQueryParamValue(entry->second, true); - } - return GURL(result); -} - -void DeviceManagementRequestJobImpl::ConfigureRequest( - net::URLFetcher* fetcher) { - fetcher->SetRequestContext(request_context_); - fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SAVE_COOKIES | - net::LOAD_DISABLE_CACHE | - (bypass_proxy_ ? net::LOAD_BYPASS_PROXY : 0)); - std::string payload; - CHECK(request_.SerializeToString(&payload)); - fetcher->SetUploadData(kPostContentType, payload); - std::string extra_headers; - if (!gaia_token_.empty()) - extra_headers += kServiceTokenAuthHeader + gaia_token_ + "\n"; - if (!dm_token_.empty()) - extra_headers += kDMTokenAuthHeader + dm_token_ + "\n"; - fetcher->SetExtraRequestHeaders(extra_headers); -} - -bool DeviceManagementRequestJobImpl::ShouldRetry( - const net::URLFetcher* fetcher) { - if (FailedWithProxy(fetcher) && !bypass_proxy_) { - // Retry the job if it failed due to a broken proxy, by bypassing the - // proxy on the next try. - bypass_proxy_ = true; - return true; - } - - // Early device policy fetches on ChromeOS and Auto-Enrollment checks are - // often interrupted during ChromeOS startup when network change notifications - // are sent. Allowing the fetcher to retry once after that is enough to - // recover; allow it to retry up to 3 times just in case. - if (fetcher->GetStatus().error() == net::ERR_NETWORK_CHANGED && - retries_count_ < kMaxNetworkChangedRetries) { - ++retries_count_; - return true; - } - - // The request didn't fail, or the limit of retry attempts has been reached; - // forward the result to the job owner. - return false; -} - -void DeviceManagementRequestJobImpl::PrepareRetry() { - if (!retry_callback_.is_null()) - retry_callback_.Run(this); -} - -void DeviceManagementRequestJobImpl::ReportError(DeviceManagementStatus code) { - em::DeviceManagementResponse dummy_response; - callback_.Run(code, net::OK, dummy_response); -} - -DeviceManagementRequestJob::~DeviceManagementRequestJob() {} - -void DeviceManagementRequestJob::SetGaiaToken(const std::string& gaia_token) { - gaia_token_ = gaia_token; -} - -void DeviceManagementRequestJob::SetOAuthToken(const std::string& oauth_token) { - AddParameter(dm_protocol::kParamOAuthToken, oauth_token); -} - -void DeviceManagementRequestJob::SetUserAffiliation( - UserAffiliation user_affiliation) { - AddParameter(dm_protocol::kParamUserAffiliation, - UserAffiliationToString(user_affiliation)); -} - -void DeviceManagementRequestJob::SetDMToken(const std::string& dm_token) { - dm_token_ = dm_token; -} - -void DeviceManagementRequestJob::SetClientID(const std::string& client_id) { - AddParameter(dm_protocol::kParamDeviceID, client_id); -} - -em::DeviceManagementRequest* DeviceManagementRequestJob::GetRequest() { - return &request_; -} - -DeviceManagementRequestJob::DeviceManagementRequestJob( - JobType type, - const std::string& agent_parameter, - const std::string& platform_parameter) { - AddParameter(dm_protocol::kParamRequest, JobTypeToRequestType(type)); - AddParameter(dm_protocol::kParamDeviceType, dm_protocol::kValueDeviceType); - AddParameter(dm_protocol::kParamAppType, dm_protocol::kValueAppType); - AddParameter(dm_protocol::kParamAgent, agent_parameter); - AddParameter(dm_protocol::kParamPlatform, platform_parameter); -} - -void DeviceManagementRequestJob::SetRetryCallback( - const RetryCallback& retry_callback) { - retry_callback_ = retry_callback; -} - -void DeviceManagementRequestJob::Start(const Callback& callback) { - callback_ = callback; - Run(); -} - -void DeviceManagementRequestJob::AddParameter(const std::string& name, - const std::string& value) { - query_params_.push_back(std::make_pair(name, value)); -} - -// A random value that other fetchers won't likely use. -const int DeviceManagementService::kURLFetcherID = 0xde71ce1d; - -DeviceManagementService::~DeviceManagementService() { - // All running jobs should have been cancelled by now. - DCHECK(pending_jobs_.empty()); - DCHECK(queued_jobs_.empty()); -} - -DeviceManagementRequestJob* DeviceManagementService::CreateJob( - DeviceManagementRequestJob::JobType type, - net::URLRequestContextGetter* request_context) { - return new DeviceManagementRequestJobImpl( - type, - configuration_->GetAgentParameter(), - configuration_->GetPlatformParameter(), - this, - request_context); -} - -void DeviceManagementService::ScheduleInitialization(int64 delay_milliseconds) { - if (initialized_) - return; - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - base::Bind(&DeviceManagementService::Initialize, - weak_ptr_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(delay_milliseconds)); -} - -void DeviceManagementService::Initialize() { - if (initialized_) - return; - initialized_ = true; - - while (!queued_jobs_.empty()) { - StartJob(queued_jobs_.front()); - queued_jobs_.pop_front(); - } -} - -void DeviceManagementService::Shutdown() { - for (JobFetcherMap::iterator job(pending_jobs_.begin()); - job != pending_jobs_.end(); - ++job) { - delete job->first; - queued_jobs_.push_back(job->second); - } - pending_jobs_.clear(); -} - -DeviceManagementService::DeviceManagementService( - scoped_ptr<Configuration> configuration) - : configuration_(configuration.Pass()), - initialized_(false), - weak_ptr_factory_(this) { - DCHECK(configuration_); -} - -void DeviceManagementService::StartJob(DeviceManagementRequestJobImpl* job) { - std::string server_url = GetServerURL(); - net::URLFetcher* fetcher = net::URLFetcher::Create( - kURLFetcherID, job->GetURL(server_url), net::URLFetcher::POST, this); - job->ConfigureRequest(fetcher); - pending_jobs_[fetcher] = job; - fetcher->Start(); -} - -std::string DeviceManagementService::GetServerURL() { - return configuration_->GetServerUrl(); -} - -void DeviceManagementService::OnURLFetchComplete( - const net::URLFetcher* source) { - JobFetcherMap::iterator entry(pending_jobs_.find(source)); - if (entry == pending_jobs_.end()) { - NOTREACHED() << "Callback from foreign URL fetcher"; - return; - } - - DeviceManagementRequestJobImpl* job = entry->second; - pending_jobs_.erase(entry); - - if (job->ShouldRetry(source)) { - VLOG(1) << "Retrying dmserver request."; - job->PrepareRetry(); - StartJob(job); - } else { - std::string data; - source->GetResponseAsString(&data); - job->HandleResponse(source->GetStatus(), source->GetResponseCode(), - source->GetCookies(), data); - } - delete source; -} - -void DeviceManagementService::AddJob(DeviceManagementRequestJobImpl* job) { - if (initialized_) - StartJob(job); - else - queued_jobs_.push_back(job); -} - -void DeviceManagementService::RemoveJob(DeviceManagementRequestJobImpl* job) { - for (JobFetcherMap::iterator entry(pending_jobs_.begin()); - entry != pending_jobs_.end(); - ++entry) { - if (entry->second == job) { - delete entry->first; - pending_jobs_.erase(entry); - return; - } - } - - const JobQueue::iterator elem = - std::find(queued_jobs_.begin(), queued_jobs_.end(), job); - if (elem != queued_jobs_.end()) - queued_jobs_.erase(elem); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/device_management_service.h b/chrome/browser/policy/cloud/device_management_service.h deleted file mode 100644 index 12ee862..0000000 --- a/chrome/browser/policy/cloud/device_management_service.h +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_DEVICE_MANAGEMENT_SERVICE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_DEVICE_MANAGEMENT_SERVICE_H_ - -#include <deque> -#include <map> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "net/url_request/url_fetcher_delegate.h" - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -class DeviceManagementRequestJobImpl; -class DeviceManagementService; - -// DeviceManagementRequestJob describes a request to send to the device -// management service. Jobs are created by DeviceManagementService. They can be -// canceled by deleting the object. -class DeviceManagementRequestJob { - public: - // Describes the job type. - enum JobType { - TYPE_AUTO_ENROLLMENT, - TYPE_REGISTRATION, - TYPE_API_AUTH_CODE_FETCH, - TYPE_POLICY_FETCH, - TYPE_UNREGISTRATION, - TYPE_UPLOAD_CERTIFICATE, - }; - - typedef base::Callback< - void(DeviceManagementStatus, int, - const enterprise_management::DeviceManagementResponse&)> Callback; - - typedef base::Callback<void(DeviceManagementRequestJob*)> RetryCallback; - - virtual ~DeviceManagementRequestJob(); - - // Functions for configuring the job. These should only be called before - // Start()ing the job, but never afterwards. - void SetGaiaToken(const std::string& gaia_token); - void SetOAuthToken(const std::string& oauth_token); - void SetUserAffiliation(UserAffiliation user_affiliation); - void SetDMToken(const std::string& dm_token); - void SetClientID(const std::string& client_id); - enterprise_management::DeviceManagementRequest* GetRequest(); - - // A job may automatically retry if it fails due to a temporary condition, or - // due to proxy misconfigurations. If a |retry_callback| is set then it will - // be invoked with the DeviceManagementRequestJob as an argument when that - // happens, so that the job's owner can customize the retry request before - // it's sent. - void SetRetryCallback(const RetryCallback& retry_callback); - - // Starts the job. |callback| will be invoked on completion. - void Start(const Callback& callback); - - protected: - typedef std::vector<std::pair<std::string, std::string> > ParameterMap; - - DeviceManagementRequestJob(JobType type, - const std::string& agent_parameter, - const std::string& platform_parameter); - - // Appends a parameter to |query_params|. - void AddParameter(const std::string& name, const std::string& value); - - // Fires the job, to be filled in by implementations. - virtual void Run() = 0; - - ParameterMap query_params_; - std::string gaia_token_; - std::string dm_token_; - enterprise_management::DeviceManagementRequest request_; - RetryCallback retry_callback_; - - Callback callback_; - - private: - DISALLOW_COPY_AND_ASSIGN(DeviceManagementRequestJob); -}; - -// The device management service is responsible for everything related to -// communication with the device management server. It creates the backends -// objects that the device management policy provider and friends use to issue -// requests. -class DeviceManagementService : public net::URLFetcherDelegate { - public: - // Obtains the parameters used to contact the server. - // This allows creating the DeviceManagementService early and getting these - // parameters later. Passing the parameters directly in the ctor isn't - // possible because some aren't ready during startup. http://crbug.com/302798 - class Configuration { - public: - virtual ~Configuration() {} - - // Server at which to contact the service. - virtual std::string GetServerUrl() = 0; - - // Agent reported in the "agent" query parameter. - virtual std::string GetAgentParameter() = 0; - - // The platform reported in the "platform" query parameter. - virtual std::string GetPlatformParameter() = 0; - }; - - explicit DeviceManagementService(scoped_ptr<Configuration> configuration); - virtual ~DeviceManagementService(); - - // The ID of URLFetchers created by the DeviceManagementService. This can be - // used by tests that use a TestURLFetcherFactory to get the pending fetchers - // created by the DeviceManagementService. - static const int kURLFetcherID; - - // Creates a new device management request job. Ownership is transferred to - // the caller. - virtual DeviceManagementRequestJob* CreateJob( - DeviceManagementRequestJob::JobType type, - net::URLRequestContextGetter* request_context); - - // Schedules a task to run |Initialize| after |delay_milliseconds| had passed. - void ScheduleInitialization(int64 delay_milliseconds); - - // Makes the service stop all requests. - void Shutdown(); - - // Gets the URL that the DMServer requests are sent to. - std::string GetServerURL(); - - private: - typedef std::map<const net::URLFetcher*, - DeviceManagementRequestJobImpl*> JobFetcherMap; - typedef std::deque<DeviceManagementRequestJobImpl*> JobQueue; - - friend class DeviceManagementRequestJobImpl; - - // net::URLFetcherDelegate override. - virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; - - // Starts processing any queued jobs. - void Initialize(); - - // Starts a job. - void StartJob(DeviceManagementRequestJobImpl* job); - - // Adds a job. Caller must make sure the job pointer stays valid until the job - // completes or gets canceled via RemoveJob(). - void AddJob(DeviceManagementRequestJobImpl* job); - - // Removes a job. The job will be removed and won't receive a completion - // callback. - void RemoveJob(DeviceManagementRequestJobImpl* job); - - // A Configuration implementation that is used to obtain various parameters - // used to talk to the device management server. - scoped_ptr<Configuration> configuration_; - - // The jobs we currently have in flight. - JobFetcherMap pending_jobs_; - - // Jobs that are registered, but not started yet. - JobQueue queued_jobs_; - - // If this service is initialized, incoming requests get fired instantly. - // If it is not initialized, incoming requests are queued. - bool initialized_; - - // Used to create tasks to run |Initialize| delayed on the UI thread. - base::WeakPtrFactory<DeviceManagementService> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(DeviceManagementService); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_DEVICE_MANAGEMENT_SERVICE_H_ diff --git a/chrome/browser/policy/cloud/device_management_service_browsertest.cc b/chrome/browser/policy/cloud/device_management_service_browsertest.cc index fe95063..6ec8b7d 100644 --- a/chrome/browser/policy/cloud/device_management_service_browsertest.cc +++ b/chrome/browser/policy/cloud/device_management_service_browsertest.cc @@ -8,12 +8,12 @@ #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" #include "chrome/browser/policy/cloud/test_request_interceptor.h" #include "chrome/browser/policy/test/local_policy_test_server.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/mock_device_management_service.h" #include "content/public/browser/browser_thread.h" #include "net/base/upload_bytes_element_reader.h" #include "net/base/upload_data_stream.h" diff --git a/chrome/browser/policy/cloud/device_management_service_unittest.cc b/chrome/browser/policy/cloud/device_management_service_unittest.cc deleted file mode 100644 index e9a7490..0000000 --- a/chrome/browser/policy/cloud/device_management_service_unittest.cc +++ /dev/null @@ -1,704 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <ostream> -#include <vector> - -#include "base/bind.h" -#include "base/message_loop/message_loop.h" -#include "base/message_loop/message_loop_proxy.h" -#include "base/run_loop.h" -#include "base/strings/string_split.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" -#include "net/base/escape.h" -#include "net/base/load_flags.h" -#include "net/base/net_errors.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::Mock; -using testing::_; - -namespace em = enterprise_management; - -namespace policy { - -const char kServiceUrl[] = "https://example.com/management_service"; - -// Encoded empty response messages for testing the error code paths. -const char kResponseEmpty[] = "\x08\x00"; - -#define PROTO_STRING(name) (std::string(name, arraysize(name) - 1)) - -// Some helper constants. -const char kGaiaAuthToken[] = "gaia-auth-token"; -const char kOAuthToken[] = "oauth-token"; -const char kDMToken[] = "device-management-token"; -const char kClientID[] = "device-id"; -const char kRobotAuthCode[] = "robot-oauth-auth-code"; - -// Unit tests for the device management policy service. The tests are run -// against a TestURLFetcherFactory that is used to short-circuit the request -// without calling into the actual network stack. -class DeviceManagementServiceTestBase : public testing::Test { - protected: - DeviceManagementServiceTestBase() { - request_context_ = - new net::TestURLRequestContextGetter(loop_.message_loop_proxy()); - ResetService(); - InitializeService(); - } - - ~DeviceManagementServiceTestBase() { - service_.reset(); - base::RunLoop().RunUntilIdle(); - } - - void ResetService() { - scoped_ptr<DeviceManagementService::Configuration> configuration( - new MockDeviceManagementServiceConfiguration(kServiceUrl)); - service_.reset(new DeviceManagementService(configuration.Pass())); - } - - void InitializeService() { - service_->ScheduleInitialization(0); - base::RunLoop().RunUntilIdle(); - } - - net::TestURLFetcher* GetFetcher() { - return factory_.GetFetcherByID(DeviceManagementService::kURLFetcherID); - } - - DeviceManagementRequestJob* StartRegistrationJob() { - DeviceManagementRequestJob* job = - service_->CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, - request_context_); - job->SetGaiaToken(kGaiaAuthToken); - job->SetOAuthToken(kOAuthToken); - job->SetClientID(kClientID); - job->GetRequest()->mutable_register_request(); - job->SetRetryCallback(base::Bind( - &DeviceManagementServiceTestBase::OnJobRetry, base::Unretained(this))); - job->Start(base::Bind(&DeviceManagementServiceTestBase::OnJobDone, - base::Unretained(this))); - return job; - } - - DeviceManagementRequestJob* StartApiAuthCodeFetchJob() { - DeviceManagementRequestJob* job = service_->CreateJob( - DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH, - request_context_); - job->SetGaiaToken(kGaiaAuthToken); - job->SetOAuthToken(kOAuthToken); - job->SetClientID(kClientID); - job->GetRequest()->mutable_service_api_access_request(); - job->SetRetryCallback(base::Bind( - &DeviceManagementServiceTestBase::OnJobRetry, base::Unretained(this))); - job->Start(base::Bind(&DeviceManagementServiceTestBase::OnJobDone, - base::Unretained(this))); - return job; - } - - DeviceManagementRequestJob* StartUnregistrationJob() { - DeviceManagementRequestJob* job = - service_->CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, - request_context_); - job->SetDMToken(kDMToken); - job->SetClientID(kClientID); - job->GetRequest()->mutable_unregister_request(); - job->SetRetryCallback(base::Bind( - &DeviceManagementServiceTestBase::OnJobRetry, base::Unretained(this))); - job->Start(base::Bind(&DeviceManagementServiceTestBase::OnJobDone, - base::Unretained(this))); - return job; - } - - DeviceManagementRequestJob* StartPolicyFetchJob() { - DeviceManagementRequestJob* job = - service_->CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, - request_context_); - job->SetGaiaToken(kGaiaAuthToken); - job->SetOAuthToken(kOAuthToken); - job->SetClientID(kClientID); - em::PolicyFetchRequest* fetch_request = - job->GetRequest()->mutable_policy_request()->add_request(); - fetch_request->set_policy_type(dm_protocol::kChromeUserPolicyType); - job->SetRetryCallback(base::Bind( - &DeviceManagementServiceTestBase::OnJobRetry, base::Unretained(this))); - job->Start(base::Bind(&DeviceManagementServiceTestBase::OnJobDone, - base::Unretained(this))); - return job; - } - - DeviceManagementRequestJob* StartAutoEnrollmentJob() { - DeviceManagementRequestJob* job = - service_->CreateJob(DeviceManagementRequestJob::TYPE_AUTO_ENROLLMENT, - request_context_); - job->SetClientID(kClientID); - em::DeviceAutoEnrollmentRequest* request = - job->GetRequest()->mutable_auto_enrollment_request(); - request->set_modulus(1); - request->set_remainder(0); - job->SetRetryCallback(base::Bind( - &DeviceManagementServiceTestBase::OnJobRetry, base::Unretained(this))); - job->Start(base::Bind(&DeviceManagementServiceTestBase::OnJobDone, - base::Unretained(this))); - return job; - } - - void SendResponse(net::TestURLFetcher* fetcher, - const net::URLRequestStatus request_status, - int http_status, - const std::string& response) { - fetcher->set_url(GURL(kServiceUrl)); - fetcher->set_status(request_status); - fetcher->set_response_code(http_status); - fetcher->SetResponseString(response); - fetcher->delegate()->OnURLFetchComplete(fetcher); - } - - MOCK_METHOD3(OnJobDone, void(DeviceManagementStatus, int, - const em::DeviceManagementResponse&)); - - MOCK_METHOD1(OnJobRetry, void(DeviceManagementRequestJob*)); - - base::MessageLoop loop_; - scoped_refptr<net::TestURLRequestContextGetter> request_context_; - net::TestURLFetcherFactory factory_; - scoped_ptr<DeviceManagementService> service_; -}; - -struct FailedRequestParams { - FailedRequestParams(DeviceManagementStatus expected_status, - net::URLRequestStatus::Status request_status, - int http_status, - const std::string& response) - : expected_status_(expected_status), - request_status_(request_status, 0), - http_status_(http_status), - response_(response) {} - - DeviceManagementStatus expected_status_; - net::URLRequestStatus request_status_; - int http_status_; - std::string response_; -}; - -void PrintTo(const FailedRequestParams& params, std::ostream* os) { - *os << "FailedRequestParams " << params.expected_status_ - << " " << params.request_status_.status() - << " " << params.http_status_; -} - -// A parameterized test case for erroneous response situations, they're mostly -// the same for all kinds of requests. -class DeviceManagementServiceFailedRequestTest - : public DeviceManagementServiceTestBase, - public testing::WithParamInterface<FailedRequestParams> { -}; - -TEST_P(DeviceManagementServiceFailedRequestTest, RegisterRequest) { - EXPECT_CALL(*this, OnJobDone(GetParam().expected_status_, _, _)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - SendResponse(fetcher, GetParam().request_status_, GetParam().http_status_, - GetParam().response_); -} - -TEST_P(DeviceManagementServiceFailedRequestTest, ApiAuthCodeFetchRequest) { - EXPECT_CALL(*this, OnJobDone(GetParam().expected_status_, _, _)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job( - StartApiAuthCodeFetchJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - SendResponse(fetcher, GetParam().request_status_, GetParam().http_status_, - GetParam().response_); -} - -TEST_P(DeviceManagementServiceFailedRequestTest, UnregisterRequest) { - EXPECT_CALL(*this, OnJobDone(GetParam().expected_status_, _, _)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartUnregistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - SendResponse(fetcher, GetParam().request_status_, GetParam().http_status_, - GetParam().response_); -} - -TEST_P(DeviceManagementServiceFailedRequestTest, PolicyRequest) { - EXPECT_CALL(*this, OnJobDone(GetParam().expected_status_, _, _)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartPolicyFetchJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - SendResponse(fetcher, GetParam().request_status_, GetParam().http_status_, - GetParam().response_); -} - -TEST_P(DeviceManagementServiceFailedRequestTest, AutoEnrollmentRequest) { - EXPECT_CALL(*this, OnJobDone(GetParam().expected_status_, _, _)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartAutoEnrollmentJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - SendResponse(fetcher, GetParam().request_status_, GetParam().http_status_, - GetParam().response_); -} - -INSTANTIATE_TEST_CASE_P( - DeviceManagementServiceFailedRequestTestInstance, - DeviceManagementServiceFailedRequestTest, - testing::Values( - FailedRequestParams( - DM_STATUS_REQUEST_FAILED, - net::URLRequestStatus::FAILED, - 200, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_HTTP_STATUS_ERROR, - net::URLRequestStatus::SUCCESS, - 666, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_RESPONSE_DECODING_ERROR, - net::URLRequestStatus::SUCCESS, - 200, - PROTO_STRING("Not a protobuf.")), - FailedRequestParams( - DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED, - net::URLRequestStatus::SUCCESS, - 403, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER, - net::URLRequestStatus::SUCCESS, - 405, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_SERVICE_DEVICE_ID_CONFLICT, - net::URLRequestStatus::SUCCESS, - 409, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_SERVICE_DEVICE_NOT_FOUND, - net::URLRequestStatus::SUCCESS, - 410, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID, - net::URLRequestStatus::SUCCESS, - 401, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_REQUEST_INVALID, - net::URLRequestStatus::SUCCESS, - 400, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_TEMPORARY_UNAVAILABLE, - net::URLRequestStatus::SUCCESS, - 404, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_SERVICE_ACTIVATION_PENDING, - net::URLRequestStatus::SUCCESS, - 412, - PROTO_STRING(kResponseEmpty)), - FailedRequestParams( - DM_STATUS_SERVICE_MISSING_LICENSES, - net::URLRequestStatus::SUCCESS, - 402, - PROTO_STRING(kResponseEmpty)))); - -// Simple query parameter parser for testing. -class QueryParams { - public: - explicit QueryParams(const std::string& query) { - base::SplitStringIntoKeyValuePairs(query, '=', '&', ¶ms_); - } - - bool Check(const std::string& name, const std::string& expected_value) { - bool found = false; - for (ParamMap::const_iterator i(params_.begin()); i != params_.end(); ++i) { - std::string unescaped_name(net::UnescapeURLComponent( - i->first, - net::UnescapeRule::NORMAL | - net::UnescapeRule::SPACES | - net::UnescapeRule::URL_SPECIAL_CHARS | - net::UnescapeRule::CONTROL_CHARS | - net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); - if (unescaped_name == name) { - if (found) - return false; - found = true; - std::string unescaped_value(net::UnescapeURLComponent( - i->second, - net::UnescapeRule::NORMAL | - net::UnescapeRule::SPACES | - net::UnescapeRule::URL_SPECIAL_CHARS | - net::UnescapeRule::CONTROL_CHARS | - net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); - if (unescaped_value != expected_value) - return false; - } - } - return found; - } - - private: - typedef std::vector<std::pair<std::string, std::string> > ParamMap; - ParamMap params_; -}; - -class DeviceManagementServiceTest - : public DeviceManagementServiceTestBase { - protected: - void CheckURLAndQueryParams(const GURL& request_url, - const std::string& request_type, - const std::string& device_id) { - const GURL service_url(kServiceUrl); - EXPECT_EQ(service_url.scheme(), request_url.scheme()); - EXPECT_EQ(service_url.host(), request_url.host()); - EXPECT_EQ(service_url.port(), request_url.port()); - EXPECT_EQ(service_url.path(), request_url.path()); - - QueryParams query_params(request_url.query()); - EXPECT_TRUE(query_params.Check(dm_protocol::kParamRequest, request_type)); - EXPECT_TRUE(query_params.Check(dm_protocol::kParamDeviceID, device_id)); - EXPECT_TRUE(query_params.Check(dm_protocol::kParamDeviceType, - dm_protocol::kValueDeviceType)); - EXPECT_TRUE(query_params.Check(dm_protocol::kParamAppType, - dm_protocol::kValueAppType)); - } -}; - -MATCHER_P(MessageEquals, reference, "") { - std::string reference_data; - std::string arg_data; - return arg.SerializeToString(&arg_data) && - reference.SerializeToString(&reference_data) && - arg_data == reference_data; -} - -TEST_F(DeviceManagementServiceTest, RegisterRequest) { - em::DeviceManagementResponse expected_response; - expected_response.mutable_register_response()-> - set_device_management_token(kDMToken); - EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, - MessageEquals(expected_response))); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - CheckURLAndQueryParams(fetcher->GetOriginalURL(), - dm_protocol::kValueRequestRegister, - kClientID); - - std::string expected_data; - ASSERT_TRUE(request_job->GetRequest()->SerializeToString(&expected_data)); - EXPECT_EQ(expected_data, fetcher->upload_data()); - - // Generate the response. - std::string response_data; - ASSERT_TRUE(expected_response.SerializeToString(&response_data)); - net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); - SendResponse(fetcher, status, 200, response_data); -} - -TEST_F(DeviceManagementServiceTest, ApiAuthCodeFetchRequest) { - em::DeviceManagementResponse expected_response; - expected_response.mutable_service_api_access_response()->set_auth_code( - kRobotAuthCode); - EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, - MessageEquals(expected_response))); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job( - StartApiAuthCodeFetchJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - CheckURLAndQueryParams(fetcher->GetOriginalURL(), - dm_protocol::kValueRequestApiAuthorization, - kClientID); - - std::string expected_data; - ASSERT_TRUE(request_job->GetRequest()->SerializeToString(&expected_data)); - EXPECT_EQ(expected_data, fetcher->upload_data()); - - // Generate the response. - std::string response_data; - ASSERT_TRUE(expected_response.SerializeToString(&response_data)); - net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); - SendResponse(fetcher, status, 200, response_data); -} - -TEST_F(DeviceManagementServiceTest, UnregisterRequest) { - em::DeviceManagementResponse expected_response; - expected_response.mutable_unregister_response(); - EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, - MessageEquals(expected_response))); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartUnregistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - // Check the data the fetcher received. - const GURL& request_url(fetcher->GetOriginalURL()); - const GURL service_url(kServiceUrl); - EXPECT_EQ(service_url.scheme(), request_url.scheme()); - EXPECT_EQ(service_url.host(), request_url.host()); - EXPECT_EQ(service_url.port(), request_url.port()); - EXPECT_EQ(service_url.path(), request_url.path()); - - CheckURLAndQueryParams(fetcher->GetOriginalURL(), - dm_protocol::kValueRequestUnregister, - kClientID); - - std::string expected_data; - ASSERT_TRUE(request_job->GetRequest()->SerializeToString(&expected_data)); - EXPECT_EQ(expected_data, fetcher->upload_data()); - - // Generate the response. - std::string response_data; - ASSERT_TRUE(expected_response.SerializeToString(&response_data)); - net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); - SendResponse(fetcher, status, 200, response_data); -} - -TEST_F(DeviceManagementServiceTest, CancelRegisterRequest) { - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - // There shouldn't be any callbacks. - request_job.reset(); -} - -TEST_F(DeviceManagementServiceTest, CancelApiAuthCodeFetch) { - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job( - StartApiAuthCodeFetchJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - // There shouldn't be any callbacks. - request_job.reset(); -} - -TEST_F(DeviceManagementServiceTest, CancelUnregisterRequest) { - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartUnregistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - // There shouldn't be any callbacks. - request_job.reset(); -} - -TEST_F(DeviceManagementServiceTest, CancelPolicyRequest) { - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartPolicyFetchJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - // There shouldn't be any callbacks. - request_job.reset(); -} - -TEST_F(DeviceManagementServiceTest, JobQueueing) { - // Start with a non-initialized service. - ResetService(); - - em::DeviceManagementResponse expected_response; - expected_response.mutable_register_response()-> - set_device_management_token(kDMToken); - EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, - MessageEquals(expected_response))); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - - // Make a request. We should not see any fetchers being created. - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_FALSE(fetcher); - - // Now initialize the service. That should start the job. - InitializeService(); - fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - factory_.RemoveFetcherFromMap(DeviceManagementService::kURLFetcherID); - - // Check that the request is processed as expected. - std::string response_data; - ASSERT_TRUE(expected_response.SerializeToString(&response_data)); - net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); - SendResponse(fetcher, status, 200, response_data); -} - -TEST_F(DeviceManagementServiceTest, CancelRequestAfterShutdown) { - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - scoped_ptr<DeviceManagementRequestJob> request_job(StartPolicyFetchJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - // Shutdown the service and cancel the job afterwards. - service_->Shutdown(); - request_job.reset(); -} - -ACTION_P(ResetPointer, pointer) { - pointer->reset(); -} - -TEST_F(DeviceManagementServiceTest, CancelDuringCallback) { - // Make a request. - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - - EXPECT_CALL(*this, OnJobDone(_, _, _)) - .WillOnce(ResetPointer(&request_job)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - - // Generate a callback. - net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0); - SendResponse(fetcher, status, 500, std::string()); - - // Job should have been reset. - EXPECT_FALSE(request_job.get()); -} - -TEST_F(DeviceManagementServiceTest, RetryOnProxyError) { - // Make a request. - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)); - - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_TRUE((fetcher->GetLoadFlags() & net::LOAD_BYPASS_PROXY) == 0); - const GURL original_url(fetcher->GetOriginalURL()); - const std::string upload_data(fetcher->upload_data()); - - // Generate a callback with a proxy failure. - net::URLRequestStatus status(net::URLRequestStatus::FAILED, - net::ERR_PROXY_CONNECTION_FAILED); - SendResponse(fetcher, status, 200, std::string()); - - // Verify that a new URLFetcher was started that bypasses the proxy. - fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_TRUE(fetcher->GetLoadFlags() & net::LOAD_BYPASS_PROXY); - EXPECT_EQ(original_url, fetcher->GetOriginalURL()); - EXPECT_EQ(upload_data, fetcher->upload_data()); -} - -TEST_F(DeviceManagementServiceTest, RetryOnBadResponseFromProxy) { - // Make a request. - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)); - - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_TRUE((fetcher->GetLoadFlags() & net::LOAD_BYPASS_PROXY) == 0); - const GURL original_url(fetcher->GetOriginalURL()); - const std::string upload_data(fetcher->upload_data()); - fetcher->set_was_fetched_via_proxy(true); - scoped_refptr<net::HttpResponseHeaders> headers; - headers = new net::HttpResponseHeaders( - "HTTP/1.1 200 OK\0Content-type: bad/type\0\0"); - fetcher->set_response_headers(headers); - - // Generate a callback with a valid http response, that was generated by - // a bad/wrong proxy. - net::URLRequestStatus status; - SendResponse(fetcher, status, 200, std::string()); - - // Verify that a new URLFetcher was started that bypasses the proxy. - fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_TRUE((fetcher->GetLoadFlags() & net::LOAD_BYPASS_PROXY) != 0); - EXPECT_EQ(original_url, fetcher->GetOriginalURL()); - EXPECT_EQ(upload_data, fetcher->upload_data()); -} - -TEST_F(DeviceManagementServiceTest, RetryOnNetworkChanges) { - // Make a request. - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)); - - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - const GURL original_url(fetcher->GetOriginalURL()); - const std::string original_upload_data(fetcher->upload_data()); - - // Make it fail with ERR_NETWORK_CHANGED. - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_NETWORK_CHANGED)); - fetcher->set_url(GURL(kServiceUrl)); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that a new URLFetcher was started that retries this job, after - // having called OnJobRetry. - Mock::VerifyAndClearExpectations(this); - fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_EQ(original_url, fetcher->GetOriginalURL()); - EXPECT_EQ(original_upload_data, fetcher->upload_data()); - EXPECT_EQ(net::URLRequestStatus::SUCCESS, fetcher->GetStatus().status()); -} - -TEST_F(DeviceManagementServiceTest, RetryLimit) { - scoped_ptr<DeviceManagementRequestJob> request_job(StartRegistrationJob()); - - // Simulate 3 failed network requests. - for (int i = 0; i < 3; ++i) { - // Make the current fetcher fail with ERR_NETWORK_CHANGED. - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_CALL(*this, OnJobDone(_, _, _)).Times(0); - EXPECT_CALL(*this, OnJobRetry(_)); - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_NETWORK_CHANGED)); - fetcher->set_url(GURL(kServiceUrl)); - fetcher->delegate()->OnURLFetchComplete(fetcher); - Mock::VerifyAndClearExpectations(this); - } - - // At the next failure the DeviceManagementService should give up retrying and - // pass the error code to the job's owner. - net::TestURLFetcher* fetcher = GetFetcher(); - ASSERT_TRUE(fetcher); - EXPECT_CALL(*this, OnJobDone(DM_STATUS_REQUEST_FAILED, _, _)); - EXPECT_CALL(*this, OnJobRetry(_)).Times(0); - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_NETWORK_CHANGED)); - fetcher->set_url(GURL(kServiceUrl)); - fetcher->delegate()->OnURLFetchComplete(fetcher); - Mock::VerifyAndClearExpectations(this); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/enterprise_metrics.cc b/chrome/browser/policy/cloud/enterprise_metrics.cc deleted file mode 100644 index b9d4eda..0000000 --- a/chrome/browser/policy/cloud/enterprise_metrics.cc +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/enterprise_metrics.h" - -namespace policy { - -const char kMetricToken[] = "Enterprise.DMToken"; -const char kMetricPolicy[] = "Enterprise.Policy"; -const char kMetricEnrollment[] = "Enterprise.Enrollment"; -const char kMetricPolicyRefresh[] = "Enterprise.PolicyRefresh"; -const char kMetricPolicyInvalidations[] = "Enterprise.PolicyInvalidations"; - -} // namespace policy diff --git a/chrome/browser/policy/cloud/enterprise_metrics.h b/chrome/browser/policy/cloud/enterprise_metrics.h deleted file mode 100644 index 1b0c920..0000000 --- a/chrome/browser/policy/cloud/enterprise_metrics.h +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_ENTERPRISE_METRICS_H_ -#define CHROME_BROWSER_POLICY_CLOUD_ENTERPRISE_METRICS_H_ - -namespace policy { - -// Metrics collected for enterprise events. - -// Events related to fetching, saving and loading DM server tokens. -// These metrics are collected both for device and user tokens. -enum MetricToken { - // A cached token was successfully loaded from disk. - kMetricTokenLoadSucceeded, - // Reading a cached token from disk failed. - kMetricTokenLoadFailed, - - // A token fetch request was sent to the DM server. - kMetricTokenFetchRequested, - // The request was invalid, or the HTTP request failed. - kMetricTokenFetchRequestFailed, - // Error HTTP status received, or the DM server failed in another way. - kMetricTokenFetchServerFailed, - // A response to the fetch request was received. - kMetricTokenFetchResponseReceived, - // The response received was invalid. This happens when some expected data - // was not present in the response. - kMetricTokenFetchBadResponse, - // DM server reported that management is not supported. - kMetricTokenFetchManagementNotSupported, - // DM server reported that the given device ID was not found. - kMetricTokenFetchDeviceNotFound, - // DM token successfully retrieved. - kMetricTokenFetchOK, - - // Successfully cached a token to disk. - kMetricTokenStoreSucceeded, - // Caching a token to disk failed. - kMetricTokenStoreFailed, - - // DM server reported that the device-id generated is not unique. - kMetricTokenFetchDeviceIdConflict, - // DM server reported that the serial number we try to register is invalid. - kMetricTokenFetchInvalidSerialNumber, - // DM server reported that the licenses for the domain have expired or been - // exhausted. - kMetricMissingLicenses, - - kMetricTokenSize // Must be the last. -}; - -// Events related to fetching, saving and loading user and device policies. -enum MetricPolicy { - // A cached policy was successfully loaded from disk. - kMetricPolicyLoadSucceeded, - // Reading a cached policy from disk failed. - kMetricPolicyLoadFailed, - - // A policy fetch request was sent to the DM server. - kMetricPolicyFetchRequested, - // The request was invalid, or the HTTP request failed. - kMetricPolicyFetchRequestFailed, - // Error HTTP status received, or the DM server failed in another way. - kMetricPolicyFetchServerFailed, - // Policy not found for the given user or device. - kMetricPolicyFetchNotFound, - // DM server didn't accept the token used in the request. - kMetricPolicyFetchInvalidToken, - // A response to the policy fetch request was received. - kMetricPolicyFetchResponseReceived, - // The policy response message didn't contain a policy, or other data was - // missing. - kMetricPolicyFetchBadResponse, - // Failed to decode the policy. - kMetricPolicyFetchInvalidPolicy, - // The device policy was rejected because its signature was invalid. - kMetricPolicyFetchBadSignature, - // Rejected policy because its timestamp is in the future. - kMetricPolicyFetchTimestampInFuture, - // Device policy rejected because the device is not managed. - kMetricPolicyFetchNonEnterpriseDevice, - // The policy was provided for a username that is different from the device - // owner, and the policy was rejected. - kMetricPolicyFetchUserMismatch, - // The policy was rejected for another reason. Currently this can happen - // only for device policies, when the SignedSettings fail to store or retrieve - // a stored policy. - kMetricPolicyFetchOtherFailed, - // The fetched policy was accepted. - kMetricPolicyFetchOK, - // The policy just fetched didn't have any changes compared to the cached - // policy. - kMetricPolicyFetchNotModified, - - // Successfully cached a policy to disk. - kMetricPolicyStoreSucceeded, - // Caching a policy to disk failed. - kMetricPolicyStoreFailed, - - kMetricPolicySize // Must be the last. -}; - -// Events related to device enrollment. -enum MetricEnrollment { - // The enrollment screen was closed without completing the enrollment - // process. - kMetricEnrollmentCancelled, - // The user submitted credentials and started the enrollment process. - kMetricEnrollmentStarted, - // Enrollment failed due to a network error. - kMetricEnrollmentNetworkFailed, - // Enrollment failed because logging in to Gaia failed. - kMetricEnrollmentLoginFailed, - // Enrollment failed because it is not supported for the account used. - kMetricEnrollmentNotSupported, - // Enrollment failed because it failed to apply device policy. - kMetricEnrollmentPolicyFailed, - // Enrollment failed due to an unexpected error. This currently happens when - // the Gaia auth token is not issued for the DM service, the device cloud - // policy subsystem isn't initialized, or when fetching Gaia tokens fails - // for an unknown reason. - kMetricEnrollmentOtherFailed, - // Enrollment was successful. - kMetricEnrollmentOK, - // Enrollment failed because the serial number we try to register is not - // assigned to the domain used. - kMetricEnrollmentInvalidSerialNumber, - // Auto-enrollment started automatically after the user signed in. - kMetricEnrollmentAutoStarted, - // Auto-enrollment failed. - kMetricEnrollmentAutoFailed, - // Auto-enrollment was retried after having failed before. - kMetricEnrollmentAutoRetried, - // Auto-enrollment was canceled through the opt-out dialog. - kMetricEnrollmentAutoCancelled, - // Auto-enrollment succeeded. - kMetricEnrollmentAutoOK, - // Enrollment failed because the enrollment mode was not supplied by the - // DMServer or the mode is not known to the client. - kMetricEnrollmentInvalidEnrollmentMode, - // Auto-enrollment is not supported for the mode supplied by the server. - // This presently means trying to auto-enroll in kiosk mode. - kMetricEnrollmentAutoEnrollmentNotSupported, - // The lockbox initialization has taken too long to complete and the - // enrollment has been canceled because of that. - kMetricLockboxTimeoutError, - // The username used to re-enroll the device does not belong to the domain - // that the device was initially enrolled to. - kMetricEnrollmentWrongUserError, - // DM server reported that the licenses for the domain has expired or been - // exhausted. - kMetricMissingLicensesError, - // Enrollment failed because the robot account auth code couldn't be - // fetched from the DM Server. - kMetricEnrollmentRobotAuthCodeFetchFailed, - // Enrollment failed because the robot account auth code couldn't be - // exchanged for a refresh token. - kMetricEnrollmentRobotRefreshTokenFetchFailed, - // Enrollment failed because the robot account refresh token couldn't be - // persisted on the device. - kMetricEnrollmentRobotRefreshTokenStoreFailed, - - kMetricEnrollmentSize // Must be the last. -}; - -// Events related to policy refresh. -enum MetricPolicyRefresh { - // A refresh occurred while the policy was not invalidated and the policy was - // changed. Invalidations were enabled. - METRIC_POLICY_REFRESH_CHANGED, - // A refresh occurred while the policy was not invalidated and the policy was - // changed. Invalidations were disabled. - METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS, - // A refresh occurred while the policy was not invalidated and the policy was - // unchanged. - METRIC_POLICY_REFRESH_UNCHANGED, - // A refresh occurred while the policy was invalidated and the policy was - // changed. - METRIC_POLICY_REFRESH_INVALIDATED_CHANGED, - // A refresh occurred while the policy was invalidated and the policy was - // unchanged. - METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED, - - METRIC_POLICY_REFRESH_SIZE // Must be the last. -}; - -// Names for the UMA counters. They are shared from here since the events -// from the same enum above can be triggered in different files, and must use -// the same UMA histogram name. -extern const char kMetricToken[]; -extern const char kMetricPolicy[]; -extern const char kMetricEnrollment[]; -extern const char kMetricPolicyRefresh[]; -extern const char kMetricPolicyInvalidations[]; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_ENTERPRISE_METRICS_H_ diff --git a/chrome/browser/policy/cloud/external_policy_data_fetcher.cc b/chrome/browser/policy/cloud/external_policy_data_fetcher.cc deleted file mode 100644 index a2e00d5..0000000 --- a/chrome/browser/policy/cloud/external_policy_data_fetcher.cc +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/sequenced_task_runner.h" -#include "base/stl_util.h" -#include "net/base/load_flags.h" -#include "net/base/net_errors.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_status.h" - -namespace policy { - -namespace { - -// Helper that forwards the result of a fetch job from the thread that the -// ExternalPolicyDataFetcherBackend runs on to the thread that the -// ExternalPolicyDataFetcher which started the job runs on. -void ForwardJobFinished( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const ExternalPolicyDataFetcherBackend::FetchCallback& callback, - ExternalPolicyDataFetcher::Job* job, - ExternalPolicyDataFetcher::Result result, - scoped_ptr<std::string> data) { - task_runner->PostTask(FROM_HERE, - base::Bind(callback, job, result, base::Passed(&data))); -} - -// Helper that forwards a job cancelation confirmation from the thread that the -// ExternalPolicyDataFetcherBackend runs on to the thread that the -// ExternalPolicyDataFetcher which canceled the job runs on. -void ForwardJobCanceled( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const base::Closure& callback) { - task_runner->PostTask(FROM_HERE, callback); -} - -// Helper invoked when a job cancelation confirmation has been forwarded to the -// thread which canceled the job. The helper itself does nothing. It exists so -// that the |job| can be passed as base::Owned(), allowing it to be deleted on -// the correct thread and after any pending callbacks for the |job| have been -// processed. -void DoNothing(ExternalPolicyDataFetcher::Job* job) { -} - -} // namespace - -struct ExternalPolicyDataFetcher::Job { - Job(const GURL& url, - int64 max_size, - const ExternalPolicyDataFetcherBackend::FetchCallback& callback); - - const GURL url; - const int64 max_size; - const ExternalPolicyDataFetcherBackend::FetchCallback callback; - - private: - DISALLOW_COPY_AND_ASSIGN(Job); -}; - -ExternalPolicyDataFetcher::Job::Job( - const GURL& url, - int64 max_size, - const ExternalPolicyDataFetcherBackend::FetchCallback& callback) - : url(url), - max_size(max_size), - callback(callback) { -} - -ExternalPolicyDataFetcher::ExternalPolicyDataFetcher( - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_refptr<base::SequencedTaskRunner> io_task_runner, - const base::WeakPtr<ExternalPolicyDataFetcherBackend>& backend) - : task_runner_(task_runner), - io_task_runner_(io_task_runner), - backend_(backend), - weak_factory_(this) { -} - -ExternalPolicyDataFetcher::~ExternalPolicyDataFetcher() { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - for (JobSet::iterator it = jobs_.begin(); it != jobs_.end(); ++it) - CancelJob(*it); -} - -ExternalPolicyDataFetcher::Job* ExternalPolicyDataFetcher::StartJob( - const GURL& url, - int64 max_size, - const FetchCallback& callback) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - Job* job = new Job( - url, max_size, - base::Bind(&ForwardJobFinished, - task_runner_, - base::Bind(&ExternalPolicyDataFetcher::OnJobFinished, - weak_factory_.GetWeakPtr(), - callback))); - jobs_.insert(job); - io_task_runner_->PostTask( - FROM_HERE, - base::Bind(&ExternalPolicyDataFetcherBackend::StartJob, backend_, job)); - return job; -} - -void ExternalPolicyDataFetcher::CancelJob(Job* job) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - DCHECK(jobs_.find(job) != jobs_.end()); - jobs_.erase(job); - // Post a task that will cancel the |job| in the |backend_|. The |job| is - // removed from |jobs_| immediately to indicate that it has been canceled but - // is not actually deleted until the cancelation has reached the |backend_| - // and a confirmation has been posted back. This ensures that no new job can - // be allocated at the same address while an OnJobFinished() callback may - // still be pending for the canceled |job|. - io_task_runner_->PostTask( - FROM_HERE, - base::Bind(&ExternalPolicyDataFetcherBackend::CancelJob, - backend_, - job, - base::Bind(&ForwardJobCanceled, - task_runner_, - base::Bind(&DoNothing, base::Owned(job))))); -} - -void ExternalPolicyDataFetcher::OnJobFinished(const FetchCallback& callback, - Job* job, - Result result, - scoped_ptr<std::string> data) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - JobSet::iterator it = jobs_.find(job); - if (it == jobs_.end()) { - // The |job| has been canceled and removed from |jobs_| already. This can - // happen because the |backend_| runs on a different thread and a |job| may - // finish before the cancellation has reached that thread. - return; - } - callback.Run(result, data.Pass()); - jobs_.erase(it); - delete job; -} - -ExternalPolicyDataFetcherBackend::ExternalPolicyDataFetcherBackend( - scoped_refptr<base::SequencedTaskRunner> io_task_runner, - scoped_refptr<net::URLRequestContextGetter> request_context) - : io_task_runner_(io_task_runner), - request_context_(request_context), - last_fetch_id_(-1), - weak_factory_(this) { -} - -ExternalPolicyDataFetcherBackend::~ExternalPolicyDataFetcherBackend() { - DCHECK(io_task_runner_->RunsTasksOnCurrentThread()); - STLDeleteContainerPairFirstPointers(job_map_.begin(), job_map_.end()); -} - -scoped_ptr<ExternalPolicyDataFetcher> - ExternalPolicyDataFetcherBackend::CreateFrontend( - scoped_refptr<base::SequencedTaskRunner> task_runner) { - return make_scoped_ptr(new ExternalPolicyDataFetcher( - task_runner, io_task_runner_, weak_factory_.GetWeakPtr())); -} - -void ExternalPolicyDataFetcherBackend::StartJob( - ExternalPolicyDataFetcher::Job* job) { - DCHECK(io_task_runner_->RunsTasksOnCurrentThread()); - net::URLFetcher* fetcher = net::URLFetcher::Create( - ++last_fetch_id_, job->url, net::URLFetcher::GET, this); - fetcher->SetRequestContext(request_context_.get()); - fetcher->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_IS_DOWNLOAD | - net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA); - fetcher->SetAutomaticallyRetryOnNetworkChanges(3); - fetcher->Start(); - job_map_[fetcher] = job; -} - -void ExternalPolicyDataFetcherBackend::CancelJob( - ExternalPolicyDataFetcher::Job* job, - const base::Closure& callback) { - DCHECK(io_task_runner_->RunsTasksOnCurrentThread()); - for (JobMap::iterator it = job_map_.begin(); it != job_map_.end(); ) { - if (it->second == job) { - delete it->first; - job_map_.erase(it++); - } else { - ++it; - } - } - callback.Run(); -} - -void ExternalPolicyDataFetcherBackend::OnURLFetchComplete( - const net::URLFetcher* source) { - DCHECK(io_task_runner_->RunsTasksOnCurrentThread()); - JobMap::iterator it = job_map_.find(const_cast<net::URLFetcher*>(source)); - if (it == job_map_.end()) { - NOTREACHED(); - return; - } - - ExternalPolicyDataFetcher::Result result = ExternalPolicyDataFetcher::SUCCESS; - scoped_ptr<std::string> data; - - const net::URLRequestStatus status = it->first->GetStatus(); - if (status.error() == net::ERR_CONNECTION_RESET || - status.error() == net::ERR_TEMPORARILY_THROTTLED) { - // The connection was interrupted. - result = ExternalPolicyDataFetcher::CONNECTION_INTERRUPTED; - } else if (status.status() != net::URLRequestStatus::SUCCESS) { - // Another network error occurred. - result = ExternalPolicyDataFetcher::NETWORK_ERROR; - } else if (source->GetResponseCode() >= 500) { - // Problem at the server. - result = ExternalPolicyDataFetcher::SERVER_ERROR; - } else if (source->GetResponseCode() >= 400) { - // Client error. - result = ExternalPolicyDataFetcher::CLIENT_ERROR; - } else if (source->GetResponseCode() != 200) { - // Any other type of HTTP failure. - result = ExternalPolicyDataFetcher::HTTP_ERROR; - } else { - data.reset(new std::string); - source->GetResponseAsString(data.get()); - if (static_cast<int64>(data->size()) > it->second->max_size) { - // Received |data| exceeds maximum allowed size. - data.reset(); - result = ExternalPolicyDataFetcher::MAX_SIZE_EXCEEDED; - } - } - - ExternalPolicyDataFetcher::Job* job = it->second; - delete it->first; - job_map_.erase(it); - job->callback.Run(job, result, data.Pass()); -} - -void ExternalPolicyDataFetcherBackend::OnURLFetchDownloadProgress( - const net::URLFetcher* source, - int64 current, - int64 total) { - DCHECK(io_task_runner_->RunsTasksOnCurrentThread()); - JobMap::iterator it = job_map_.find(const_cast<net::URLFetcher*>(source)); - DCHECK(it != job_map_.end()); - if (it == job_map_.end()) - return; - - // Reject the data if it exceeds the size limit. The content length is in - // |total|, and it may be -1 when not known. - if (current > it->second->max_size || total > it->second->max_size) { - ExternalPolicyDataFetcher::Job* job = it->second; - delete it->first; - job_map_.erase(it); - job->callback.Run(job, - ExternalPolicyDataFetcher::MAX_SIZE_EXCEEDED, - scoped_ptr<std::string>()); - } -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/external_policy_data_fetcher.h b/chrome/browser/policy/cloud/external_policy_data_fetcher.h deleted file mode 100644 index 587f3a8..0000000 --- a/chrome/browser/policy/cloud/external_policy_data_fetcher.h +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_EXTERNAL_POLICY_DATA_FETCHER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_EXTERNAL_POLICY_DATA_FETCHER_H_ - -#include <map> -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "url/gurl.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace net { -class URLFetcher; -class URLRequestContextGetter; -} - -namespace policy { - -class ExternalPolicyDataFetcherBackend; - -// This class handles network fetch jobs for the ExternalPolicyDataUpdater by -// forwarding them to an ExternalPolicyDataFetcherBackend running on a different -// thread. This is necessary because the ExternalPolicyDataUpdater runs on a -// background thread where network I/O is not allowed. -// The class can be instantiated on any thread but from then on, it must be -// accessed and destroyed on the background thread that the -// ExternalPolicyDataUpdater runs on only. -class ExternalPolicyDataFetcher { - public: - // The result of a fetch job. - enum Result { - // Successful fetch. - SUCCESS, - // The connection was interrupted. - CONNECTION_INTERRUPTED, - // Another network error occurred. - NETWORK_ERROR, - // Problem at the server. - SERVER_ERROR, - // Client error. - CLIENT_ERROR, - // Any other type of HTTP failure. - HTTP_ERROR, - // Received data exceeds maximum allowed size. - MAX_SIZE_EXCEEDED, - }; - - // Encapsulates the metadata for a fetch job. - struct Job; - - // Callback invoked when a fetch job finishes. If the fetch was successful, - // the Result is SUCCESS and the scoped_ptr contains the retrieved data. - // Otherwise, Result indicates the type of error that occurred and the - // scoped_ptr is NULL. - typedef base::Callback<void(Result, scoped_ptr<std::string>)> FetchCallback; - - // |task_runner| represents the background thread that |this| runs on. - // |backend| is used to perform network I/O. It will be dereferenced and - // accessed via |io_task_runner| only. - ExternalPolicyDataFetcher( - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_refptr<base::SequencedTaskRunner> io_task_runner, - const base::WeakPtr<ExternalPolicyDataFetcherBackend>& backend); - ~ExternalPolicyDataFetcher(); - - // Fetch data from |url| and invoke |callback| with the result. See the - // documentation of FetchCallback and Result for more details. If a fetch - // should be retried after an error, it is the caller's responsibility to call - // StartJob() again. Returns an opaque job identifier. Ownership of the job - // identifier is retained by |this|. - Job* StartJob(const GURL& url, - int64 max_size, - const FetchCallback& callback); - - // Cancel the fetch job identified by |job|. The job is canceled silently, - // without invoking the |callback| that was passed to StartJob(). - void CancelJob(Job* job); - - private: - // Callback invoked when a fetch job finishes in the |backend_|. - void OnJobFinished(const FetchCallback& callback, - Job* job, - Result result, - scoped_ptr<std::string> data); - - // Task runner representing the thread that |this| runs on. - scoped_refptr<base::SequencedTaskRunner> task_runner_; - - // Task runner representing the thread on which the |backend_| runs and - // performs network I/O. - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - - // The |backend_| is used to perform network I/O. It may be dereferenced and - // accessed via |io_task_runner_| only. - base::WeakPtr<ExternalPolicyDataFetcherBackend> backend_; - - // Set that owns all currently running Jobs. - typedef std::set<Job*> JobSet; - JobSet jobs_; - - base::WeakPtrFactory<ExternalPolicyDataFetcher> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(ExternalPolicyDataFetcher); -}; - -// This class handles network I/O for one or more ExternalPolicyDataFetchers. It -// can be instantiated on any thread that is allowed to reference -// URLRequestContextGetters (in Chrome, these are the UI and IO threads) and -// CreateFrontend() may be called from the same thread after instantiation. From -// then on, it must be accessed and destroyed on the thread that handles network -// I/O only (in Chrome, this is the IO thread). -class ExternalPolicyDataFetcherBackend : public net::URLFetcherDelegate { - public: - // Callback invoked when a fetch job finishes. If the fetch was successful, - // the Result is SUCCESS and the scoped_ptr contains the retrieved data. - // Otherwise, Result indicates the type of error that occurred and the - // scoped_ptr is NULL. - typedef base::Callback<void(ExternalPolicyDataFetcher::Job*, - ExternalPolicyDataFetcher::Result, - scoped_ptr<std::string>)> FetchCallback; - - // |io_task_runner_| represents the thread that handles network I/O and that - // |this| runs on. |request_context| is used to construct URLFetchers. - ExternalPolicyDataFetcherBackend( - scoped_refptr<base::SequencedTaskRunner> io_task_runner, - scoped_refptr<net::URLRequestContextGetter> request_context); - virtual ~ExternalPolicyDataFetcherBackend(); - - // Create an ExternalPolicyDataFetcher that allows fetch jobs to be started - // from the thread represented by |task_runner|. - scoped_ptr<ExternalPolicyDataFetcher> CreateFrontend( - scoped_refptr<base::SequencedTaskRunner> task_runner); - - // Start a fetch job defined by |job|. The caller retains ownership of |job| - // and must ensure that it remains valid until the job ends, CancelJob() is - // called or |this| is destroyed. - void StartJob(ExternalPolicyDataFetcher::Job* job); - - // Cancel the fetch job defined by |job| and invoke |callback| to confirm. - void CancelJob(ExternalPolicyDataFetcher::Job* job, - const base::Closure& callback); - - // net::URLFetcherDelegate: - virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; - virtual void OnURLFetchDownloadProgress(const net::URLFetcher* source, - int64 current, - int64 total) OVERRIDE; - - private: - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - scoped_refptr<net::URLRequestContextGetter> request_context_; - - // A monotonically increasing fetch ID. Used to identify fetches in tests. - int last_fetch_id_; - - // Map that owns the net::URLFetchers for all currently running jobs and maps - // from these to the corresponding Job. - typedef std::map<net::URLFetcher*, ExternalPolicyDataFetcher::Job*> JobMap; - JobMap job_map_; - - base::WeakPtrFactory<ExternalPolicyDataFetcherBackend> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(ExternalPolicyDataFetcherBackend); -}; - - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_EXTERNAL_POLICY_DATA_FETCHER_H_ diff --git a/chrome/browser/policy/cloud/external_policy_data_fetcher_unittest.cc b/chrome/browser/policy/cloud/external_policy_data_fetcher_unittest.cc deleted file mode 100644 index 4641c03..0000000 --- a/chrome/browser/policy/cloud/external_policy_data_fetcher_unittest.cc +++ /dev/null @@ -1,496 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/compiler_specific.h" -#include "base/sequenced_task_runner.h" -#include "base/test/test_simple_task_runner.h" -#include "net/base/net_errors.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_status.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { - -namespace { - -const char* kExternalPolicyDataURLs[] = { - "http://localhost/data_1", - "http://localhost/data_2" -}; - -const int64 kExternalPolicyDataMaxSize = 5 * 1024 * 1024; // 5 MB. - -const char* kExternalPolicyDataPayload = "External policy data"; - -} // namespace - -class ExternalPolicyDataFetcherTest : public testing::Test { - protected: - ExternalPolicyDataFetcherTest(); - virtual ~ExternalPolicyDataFetcherTest(); - - // testing::Test: - virtual void SetUp() OVERRIDE; - - void StartJob(int index); - void CancelJob(int index); - - void OnJobFinished(int job_index, - ExternalPolicyDataFetcher::Result result, - scoped_ptr<std::string> data); - int GetAndResetCallbackCount(); - - net::TestURLFetcherFactory fetcher_factory_; - scoped_refptr<base::TestSimpleTaskRunner> owner_task_runner_; - scoped_refptr<base::TestSimpleTaskRunner> io_task_runner_; - scoped_ptr<ExternalPolicyDataFetcherBackend> fetcher_backend_; - scoped_ptr<ExternalPolicyDataFetcher> fetcher_; - - std::map<int, ExternalPolicyDataFetcher::Job*> jobs_; // Not owned. - - int callback_count_; - int callback_job_index_; - ExternalPolicyDataFetcher::Result callback_result_; - scoped_ptr<std::string> callback_data_; - - DISALLOW_COPY_AND_ASSIGN(ExternalPolicyDataFetcherTest); -}; - -ExternalPolicyDataFetcherTest::ExternalPolicyDataFetcherTest() - : callback_count_(0) { -} - -ExternalPolicyDataFetcherTest::~ExternalPolicyDataFetcherTest() { -} - -void ExternalPolicyDataFetcherTest::SetUp() { - fetcher_factory_.set_remove_fetcher_on_delete(true); - io_task_runner_ = new base::TestSimpleTaskRunner(); - owner_task_runner_ = new base::TestSimpleTaskRunner(); - fetcher_backend_.reset(new ExternalPolicyDataFetcherBackend( - io_task_runner_, - scoped_refptr<net::URLRequestContextGetter>())); - fetcher_.reset( - fetcher_backend_->CreateFrontend(owner_task_runner_).release()); -} - -void ExternalPolicyDataFetcherTest::StartJob(int index) { - jobs_[index] = fetcher_->StartJob( - GURL(kExternalPolicyDataURLs[index]), - kExternalPolicyDataMaxSize, - base::Bind(&ExternalPolicyDataFetcherTest::OnJobFinished, - base::Unretained(this), index)); - io_task_runner_->RunUntilIdle(); -} - -void ExternalPolicyDataFetcherTest::CancelJob(int index) { - std::map<int, ExternalPolicyDataFetcher::Job*>::iterator it = - jobs_.find(index); - ASSERT_TRUE(it != jobs_.end()); - ExternalPolicyDataFetcher::Job* job = it->second; - jobs_.erase(it); - fetcher_->CancelJob(job); -} - -void ExternalPolicyDataFetcherTest::OnJobFinished( - int job_index, - ExternalPolicyDataFetcher::Result result, - scoped_ptr<std::string> data) { - ++callback_count_; - callback_job_index_ = job_index; - callback_result_ = result; - callback_data_.reset(data.release()); - jobs_.erase(job_index); -} - -int ExternalPolicyDataFetcherTest::GetAndResetCallbackCount() { - const int callback_count = callback_count_; - callback_count_ = 0; - return callback_count; -} - -TEST_F(ExternalPolicyDataFetcherTest, Success) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the retrieved data. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SUCCESS, callback_result_); - ASSERT_TRUE(callback_data_); - EXPECT_EQ(kExternalPolicyDataPayload, *callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, MaxSizeExceeded) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Indicate that the data size will exceed maximum allowed. - fetcher->delegate()->OnURLFetchDownloadProgress( - fetcher, - kExternalPolicyDataMaxSize + 1, - -1); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the correct error code. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::MAX_SIZE_EXCEEDED, callback_result_); - EXPECT_FALSE(callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, ConnectionInterrupted) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail due to an interrupted connection. - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_CONNECTION_RESET)); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the correct error code. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::CONNECTION_INTERRUPTED, - callback_result_); - EXPECT_FALSE(callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, NetworkError) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail due to a network error. - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_NETWORK_CHANGED)); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the correct error code. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::NETWORK_ERROR, callback_result_); - EXPECT_FALSE(callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, ServerError) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail with a server error. - fetcher->set_response_code(500); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the correct error code. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SERVER_ERROR, callback_result_); - EXPECT_FALSE(callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, ClientError) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail with a client error. - fetcher->set_response_code(400); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the correct error code. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::CLIENT_ERROR, callback_result_); - EXPECT_FALSE(callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, HTTPError) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail with an HTTP error. - fetcher->set_response_code(300); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the correct error code. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::HTTP_ERROR, callback_result_); - EXPECT_FALSE(callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, Canceled) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Cancel the fetch job. - CancelJob(0); - io_task_runner_->RunUntilIdle(); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is not invoked. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(0, GetAndResetCallbackCount()); -} - -TEST_F(ExternalPolicyDataFetcherTest, SuccessfulCanceled) { - // Start a fetch job. - StartJob(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Cancel the fetch job before the successful fetch result has arrived from - // the backend. - CancelJob(0); - - // Verify that the callback is not invoked. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(0, GetAndResetCallbackCount()); -} - -TEST_F(ExternalPolicyDataFetcherTest, ParallelJobs) { - // Start two fetch jobs. - StartJob(0); - StartJob(1); - - // Verify that the second fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that the first fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the first fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the retrieved data. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SUCCESS, callback_result_); - ASSERT_TRUE(callback_data_); - EXPECT_EQ(kExternalPolicyDataPayload, *callback_data_); - - // Verify that the second fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Complete the second fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the callback is invoked with the retrieved data. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(1, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SUCCESS, callback_result_); - ASSERT_TRUE(callback_data_); - EXPECT_EQ(kExternalPolicyDataPayload, *callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, ParallelJobsFinishingOutOfOrder) { - // Start two fetch jobs. - StartJob(0); - StartJob(1); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Complete the second fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the callback is invoked with the retrieved data. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(1, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SUCCESS, callback_result_); - ASSERT_TRUE(callback_data_); - EXPECT_EQ(kExternalPolicyDataPayload, *callback_data_); - - // Verify that the first fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the first fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is invoked with the retrieved data. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(0, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SUCCESS, callback_result_); - ASSERT_TRUE(callback_data_); - EXPECT_EQ(kExternalPolicyDataPayload, *callback_data_); -} - -TEST_F(ExternalPolicyDataFetcherTest, ParallelJobsWithCancel) { - // Start two fetch jobs. - StartJob(0); - StartJob(1); - - // Verify that the second fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that the first fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Cancel the first fetch job. - CancelJob(0); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the callback is not invoked. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(0, GetAndResetCallbackCount()); - - // Verify that the second fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Complete the second fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the callback is invoked with the retrieved data. - owner_task_runner_->RunUntilIdle(); - EXPECT_EQ(1, GetAndResetCallbackCount()); - EXPECT_EQ(1, callback_job_index_); - EXPECT_EQ(ExternalPolicyDataFetcher::SUCCESS, callback_result_); - ASSERT_TRUE(callback_data_); - EXPECT_EQ(kExternalPolicyDataPayload, *callback_data_); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/external_policy_data_updater.cc b/chrome/browser/policy/cloud/external_policy_data_updater.cc deleted file mode 100644 index da2e8f1..0000000 --- a/chrome/browser/policy/cloud/external_policy_data_updater.cc +++ /dev/null @@ -1,400 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/external_policy_data_updater.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/sequenced_task_runner.h" -#include "base/sha1.h" -#include "base/stl_util.h" -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" -#include "net/base/backoff_entry.h" -#include "url/gurl.h" - -namespace policy { - -namespace { - -// Policies for exponential backoff of failed requests. There are 3 policies for -// different classes of errors. - -// For temporary errors (HTTP 500, RST, etc). -const net::BackoffEntry::Policy kRetrySoonPolicy = { - // Number of initial errors to ignore before starting to back off. - 0, - - // Initial delay in ms: 60 seconds. - 1000 * 60, - - // Factor by which the waiting time is multiplied. - 2, - - // Fuzzing percentage; this spreads delays randomly between 80% and 100% - // of the calculated time. - 0.20, - - // Maximum delay in ms: 12 hours. - 1000 * 60 * 60 * 12, - - // When to discard an entry: never. - -1, - - // |always_use_initial_delay|; false means that the initial delay is - // applied after the first error, and starts backing off from there. - false, -}; - -// For other errors (request failed, server errors). -const net::BackoffEntry::Policy kRetryLaterPolicy = { - // Number of initial errors to ignore before starting to back off. - 0, - - // Initial delay in ms: 1 hour. - 1000 * 60 * 60, - - // Factor by which the waiting time is multiplied. - 2, - - // Fuzzing percentage; this spreads delays randomly between 80% and 100% - // of the calculated time. - 0.20, - - // Maximum delay in ms: 12 hours. - 1000 * 60 * 60 * 12, - - // When to discard an entry: never. - -1, - - // |always_use_initial_delay|; false means that the initial delay is - // applied after the first error, and starts backing off from there. - false, -}; - -// When the data fails validation (maybe because the policy URL and the data -// served at that URL are out of sync). This essentially retries every 12 hours, -// with some random jitter. -const net::BackoffEntry::Policy kRetryMuchLaterPolicy = { - // Number of initial errors to ignore before starting to back off. - 0, - - // Initial delay in ms: 12 hours. - 1000 * 60 * 60 * 12, - - // Factor by which the waiting time is multiplied. - 2, - - // Fuzzing percentage; this spreads delays randomly between 80% and 100% - // of the calculated time. - 0.20, - - // Maximum delay in ms: 12 hours. - 1000 * 60 * 60 * 12, - - // When to discard an entry: never. - -1, - - // |always_use_initial_delay|; false means that the initial delay is - // applied after the first error, and starts backing off from there. - false, -}; - -// Maximum number of retries for requests that aren't likely to get a -// different response (e.g. HTTP 4xx replies). -const int kMaxLimitedRetries = 3; - -} // namespace - -class ExternalPolicyDataUpdater::FetchJob - : public base::SupportsWeakPtr<FetchJob> { - public: - FetchJob(ExternalPolicyDataUpdater* updater, - const std::string& key, - const ExternalPolicyDataUpdater::Request& request, - const ExternalPolicyDataUpdater::FetchSuccessCallback& callback); - virtual ~FetchJob(); - - const std::string& key() const; - const ExternalPolicyDataUpdater::Request& request() const; - - void Start(); - - void OnFetchFinished(ExternalPolicyDataFetcher::Result result, - scoped_ptr<std::string> data); - - private: - void OnFailed(net::BackoffEntry* backoff_entry); - void Reschedule(); - - // Always valid as long as |this| is alive. - ExternalPolicyDataUpdater* updater_; - - const std::string key_; - const ExternalPolicyDataUpdater::Request request_; - ExternalPolicyDataUpdater::FetchSuccessCallback callback_; - - // If the job is currently running, a corresponding |fetch_job_| exists in the - // |external_policy_data_fetcher_|. The job must eventually call back to the - // |updater_|'s OnJobSucceeded() or OnJobFailed() method in this case. - // If the job is currently not running, |fetch_job_| is NULL and no callbacks - // should be invoked. - ExternalPolicyDataFetcher::Job* fetch_job_; // Not owned. - - // Some errors should trigger a limited number of retries, even with backoff. - // This counts down the number of such retries to stop retrying once the limit - // is reached. - int limited_retries_remaining_; - - // Various delays to retry a failed download, depending on the failure reason. - net::BackoffEntry retry_soon_entry_; - net::BackoffEntry retry_later_entry_; - net::BackoffEntry retry_much_later_entry_; - - DISALLOW_COPY_AND_ASSIGN(FetchJob); -}; - -ExternalPolicyDataUpdater::Request::Request() { -} - -ExternalPolicyDataUpdater::Request::Request(const std::string& url, - const std::string& hash, - int64 max_size) - : url(url), hash(hash), max_size(max_size) { -} - -bool ExternalPolicyDataUpdater::Request::operator==( - const Request& other) const { - return url == other.url && hash == other.hash && max_size == other.max_size; -} - -ExternalPolicyDataUpdater::FetchJob::FetchJob( - ExternalPolicyDataUpdater* updater, - const std::string& key, - const ExternalPolicyDataUpdater::Request& request, - const ExternalPolicyDataUpdater::FetchSuccessCallback& callback) - : updater_(updater), - key_(key), - request_(request), - callback_(callback), - fetch_job_(NULL), - limited_retries_remaining_(kMaxLimitedRetries), - retry_soon_entry_(&kRetrySoonPolicy), - retry_later_entry_(&kRetryLaterPolicy), - retry_much_later_entry_(&kRetryMuchLaterPolicy) { -} - -ExternalPolicyDataUpdater::FetchJob::~FetchJob() { - if (fetch_job_) { - // Cancel the fetch job in the |external_policy_data_fetcher_|. - updater_->external_policy_data_fetcher_->CancelJob(fetch_job_); - // Inform the |updater_| that the job was canceled. - updater_->OnJobFailed(this); - } -} - -const std::string& ExternalPolicyDataUpdater::FetchJob::key() const { - return key_; -} - -const ExternalPolicyDataUpdater::Request& - ExternalPolicyDataUpdater::FetchJob::request() const { - return request_; -} - -void ExternalPolicyDataUpdater::FetchJob::Start() { - DCHECK(!fetch_job_); - // Start a fetch job in the |external_policy_data_fetcher_|. This will - // eventually call back to OnFetchFinished() with the result. - fetch_job_ = updater_->external_policy_data_fetcher_->StartJob( - GURL(request_.url), request_.max_size, - base::Bind(&ExternalPolicyDataUpdater::FetchJob::OnFetchFinished, - base::Unretained(this))); -} - -void ExternalPolicyDataUpdater::FetchJob::OnFetchFinished( - ExternalPolicyDataFetcher::Result result, - scoped_ptr<std::string> data) { - // The fetch job in the |external_policy_data_fetcher_| is finished. - fetch_job_ = NULL; - - switch (result) { - case ExternalPolicyDataFetcher::CONNECTION_INTERRUPTED: - // The connection was interrupted. Try again soon. - OnFailed(&retry_soon_entry_); - return; - case ExternalPolicyDataFetcher::NETWORK_ERROR: - // Another network error occurred. Try again later. - OnFailed(&retry_later_entry_); - return; - case ExternalPolicyDataFetcher::SERVER_ERROR: - // Problem at the server. Try again soon. - OnFailed(&retry_soon_entry_); - return; - case ExternalPolicyDataFetcher::CLIENT_ERROR: - // Client error. This is unlikely to go away. Try again later, and give up - // retrying after 3 attempts. - OnFailed(limited_retries_remaining_ ? &retry_later_entry_ : NULL); - if (limited_retries_remaining_) - --limited_retries_remaining_; - return; - case ExternalPolicyDataFetcher::HTTP_ERROR: - // Any other type of HTTP failure. Try again later. - OnFailed(&retry_later_entry_); - return; - case ExternalPolicyDataFetcher::MAX_SIZE_EXCEEDED: - // Received |data| exceeds maximum allowed size. This may be because the - // data being served is stale. Try again much later. - OnFailed(&retry_much_later_entry_); - return; - case ExternalPolicyDataFetcher::SUCCESS: - break; - } - - if (base::SHA1HashString(*data) != request_.hash) { - // Received |data| does not match expected hash. This may be because the - // data being served is stale. Try again much later. - OnFailed(&retry_much_later_entry_); - return; - } - - // If the callback rejects the data, try again much later. - if (!callback_.Run(*data)) { - OnFailed(&retry_much_later_entry_); - return; - } - - // Signal success. - updater_->OnJobSucceeded(this); -} - -void ExternalPolicyDataUpdater::FetchJob::OnFailed(net::BackoffEntry* entry) { - if (entry) { - entry->InformOfRequest(false); - - // This function may have been invoked because the job was obsoleted and is - // in the process of being deleted. If this is the case, the WeakPtr will - // become invalid and the delayed task will never run. - updater_->task_runner_->PostDelayedTask( - FROM_HERE, - base::Bind(&FetchJob::Reschedule, AsWeakPtr()), - entry->GetTimeUntilRelease()); - } - - updater_->OnJobFailed(this); -} - -void ExternalPolicyDataUpdater::FetchJob::Reschedule() { - updater_->ScheduleJob(this); -} - -ExternalPolicyDataUpdater::ExternalPolicyDataUpdater( - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher, - size_t max_parallel_fetches) - : task_runner_(task_runner), - external_policy_data_fetcher_(external_policy_data_fetcher.release()), - max_parallel_jobs_(max_parallel_fetches), - running_jobs_(0), - shutting_down_(false) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); -} - -ExternalPolicyDataUpdater::~ExternalPolicyDataUpdater() { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - shutting_down_ = true; - STLDeleteValues(&job_map_); -} - -void ExternalPolicyDataUpdater::FetchExternalData( - const std::string key, - const Request& request, - const FetchSuccessCallback& callback) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - - // Check whether a job exists for this |key| already. - FetchJob* job = job_map_[key]; - if (job) { - // If the current |job| is handling the given |request| already, nothing - // needs to be done. - if (job->request() == request) - return; - - // Otherwise, the current |job| is obsolete. If the |job| is on the queue, - // its WeakPtr will be invalidated and skipped by StartNextJobs(). If |job| - // is currently running, it will call OnJobFailed() immediately. - delete job; - job_map_.erase(key); - } - - // Start a new job to handle |request|. - job = new FetchJob(this, key, request, callback); - job_map_[key] = job; - ScheduleJob(job); -} - -void ExternalPolicyDataUpdater::CancelExternalDataFetch( - const std::string& key) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - - // If a |job| exists for this |key|, delete it. If the |job| is on the queue, - // its WeakPtr will be invalidated and skipped by StartNextJobs(). If |job| is - // currently running, it will call OnJobFailed() immediately. - std::map<std::string, FetchJob*>::iterator job = job_map_.find(key); - if (job != job_map_.end()) { - delete job->second; - job_map_.erase(job); - } -} - -void ExternalPolicyDataUpdater::StartNextJobs() { - if (shutting_down_) - return; - - while (running_jobs_ < max_parallel_jobs_ && !job_queue_.empty()) { - FetchJob* job = job_queue_.front().get(); - job_queue_.pop(); - - // Some of the jobs may have been invalidated, and have to be skipped. - if (job) { - ++running_jobs_; - // A started job will always call OnJobSucceeded() or OnJobFailed(). - job->Start(); - } - } -} - -void ExternalPolicyDataUpdater::ScheduleJob(FetchJob* job) { - DCHECK_EQ(job_map_[job->key()], job); - - job_queue_.push(job->AsWeakPtr()); - - StartNextJobs(); -} - -void ExternalPolicyDataUpdater::OnJobSucceeded(FetchJob* job) { - DCHECK(running_jobs_); - DCHECK_EQ(job_map_[job->key()], job); - - --running_jobs_; - job_map_.erase(job->key()); - delete job; - - StartNextJobs(); -} - -void ExternalPolicyDataUpdater::OnJobFailed(FetchJob* job) { - DCHECK(running_jobs_); - DCHECK_EQ(job_map_[job->key()], job); - - --running_jobs_; - - // The job is not deleted when it fails because a retry attempt may have been - // scheduled. - StartNextJobs(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/external_policy_data_updater.h b/chrome/browser/policy/cloud/external_policy_data_updater.h deleted file mode 100644 index 2ac776b..0000000 --- a/chrome/browser/policy/cloud/external_policy_data_updater.h +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_EXTERNAL_POLICY_DATA_UPDATER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_EXTERNAL_POLICY_DATA_UPDATER_H_ - -#include <map> -#include <queue> -#include <string> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace policy { - -class ExternalPolicyDataFetcher; - -// This class downloads external policy data. Given a |Request|, data is fetched -// from the |url|, verified to not exceed |max_size| and to match the expected -// |hash| and then handed to a callback that can do further verification before -// finally deciding whether the fetched data is valid. -// If a fetch is not successful or retrieves invalid data, retries are scheduled -// with exponential backoff. -// The actual fetching is handled by an ExternalPolicyDataFetcher, allowing this -// class to run on a background thread where network I/O is not possible. -class ExternalPolicyDataUpdater { - public: - struct Request { - public: - Request(); - Request(const std::string& url, const std::string& hash, int64 max_size); - - bool operator==(const Request& other) const; - - std::string url; - std::string hash; - int64 max_size; - }; - - // This callback is invoked when a fetch has successfully retrieved |data| - // that does not exceed |max_size| and matches the expected |hash|. The - // callback can do further verification to decide whether the fetched data is - // valid. - // If the callback returns |true|, the data is accepted and the |Request| is - // finished. If the callback returns |false|, the data is rejected and the - // fetch is retried after a long backoff. Note that in this case, the callback - // may be invoked multiple times as the fetch is repeated. Make sure to not - // bind base::Passed() scoped_ptrs to the callback in such cases as these - // become invalid after a callback has been run once. base::Owned() can be - // used in all cases. - typedef base::Callback<bool(const std::string&)> FetchSuccessCallback; - - // This class runs on the background thread represented by |task_runner|, - // which must support file I/O. All network I/O is forwarded to a different - // thread by the |external_policy_data_fetcher|. - ExternalPolicyDataUpdater( - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher, - size_t max_parallel_fetches); - ~ExternalPolicyDataUpdater(); - - // Fetches the external data specified in the |request|. The |key| is an - // opaque identifier. If another request for the same |key| is still pending, - // it will be canceled and replaced with the new |request|. The callback will - // be invoked after a successful fetch. See the documentation of - // |FetchSuccessCallback| for more details. - void FetchExternalData(const std::string key, - const Request& request, - const FetchSuccessCallback& callback); - - // Cancels the pending request identified by |key|. If no such request is - // pending, does nothing. - void CancelExternalDataFetch(const std::string& key); - - private: - class FetchJob; - - // Starts jobs from the |job_queue_| until |max_parallel_jobs_| are running or - // the queue is depleted. - void StartNextJobs(); - - // Appends |job| to the |job_queue_| and starts it immediately if less than - // |max_parallel_jobs_| are running. - void ScheduleJob(FetchJob* job); - - // Callback for jobs that succeeded. - void OnJobSucceeded(FetchJob* job); - - // Callback for jobs that failed. - void OnJobFailed(FetchJob* job); - - scoped_refptr<base::SequencedTaskRunner> task_runner_; - scoped_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher_; - - // The maximum number of jobs to run in parallel. - size_t max_parallel_jobs_; - - // The number of jobs currently running. - size_t running_jobs_; - - // Queue of jobs waiting to be run. Jobs are taken off the queue and started - // by StartNextJobs(). - std::queue<base::WeakPtr<FetchJob> > job_queue_; - - // Map that owns all existing jobs, regardless of whether they are currently - // queued, running or waiting for a retry. - std::map<std::string, FetchJob*> job_map_; - - // |True| once the destructor starts. Prevents jobs from being started during - // shutdown. - bool shutting_down_; - - DISALLOW_COPY_AND_ASSIGN(ExternalPolicyDataUpdater); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_EXTERNAL_POLICY_DATA_UPDATER_H_ diff --git a/chrome/browser/policy/cloud/external_policy_data_updater_unittest.cc b/chrome/browser/policy/cloud/external_policy_data_updater_unittest.cc deleted file mode 100644 index 7ce8e17..0000000 --- a/chrome/browser/policy/cloud/external_policy_data_updater_unittest.cc +++ /dev/null @@ -1,962 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/external_policy_data_updater.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/sha1.h" -#include "base/test/test_pending_task.h" -#include "base/test/test_simple_task_runner.h" -#include "base/time/time.h" -#include "chrome/browser/policy/cloud/external_policy_data_fetcher.h" -#include "net/base/net_errors.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_status.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -using testing::Mock; -using testing::Return; - -namespace policy { - -namespace { - -const char* kExternalPolicyDataKeys[] = {"external_policy_data_1", - "external_policy_data_2", - "external_policy_data_3"}; -const char* kExternalPolicyDataURLs[] = {"http://example.com/data_1", - "http://example.com/data_2", - "http://example.com/data_3"}; -const char* kExternalPolicyDataPayload = "External policy data"; - -const int64 kExternalPolicyDataMaxSize = 5 * 1024 * 1024; // 5 MB. - -class MockFetchSuccessCallbackListener { - public: - MOCK_METHOD2(OnFetchSuccess, bool(const std::string&, const std::string&)); - - ExternalPolicyDataUpdater::FetchSuccessCallback CreateCallback( - const std::string& key); -}; - -ExternalPolicyDataUpdater::FetchSuccessCallback - MockFetchSuccessCallbackListener::CreateCallback(const std::string& key) { - return base::Bind(&MockFetchSuccessCallbackListener::OnFetchSuccess, - base::Unretained(this), - key); -} - -} // namespace - -class ExternalPolicyDataUpdaterTest : public testing::Test { - protected: - virtual void SetUp() OVERRIDE; - - void CreateUpdater(size_t max_parallel_fetches); - ExternalPolicyDataUpdater::Request CreateRequest( - const std::string& url) const; - void RequestExternalDataFetch(int key_index, int url_index); - void RequestExternalDataFetch(int index); - - net::TestURLFetcherFactory fetcher_factory_; - MockFetchSuccessCallbackListener callback_listener_; - scoped_refptr<base::TestSimpleTaskRunner> backend_task_runner_; - scoped_refptr<base::TestSimpleTaskRunner> io_task_runner_; - scoped_ptr<ExternalPolicyDataFetcherBackend> fetcher_backend_; - scoped_ptr<ExternalPolicyDataUpdater> updater_; -}; - -void ExternalPolicyDataUpdaterTest::SetUp() { - fetcher_factory_.set_remove_fetcher_on_delete(true); - backend_task_runner_ = new base::TestSimpleTaskRunner(); - io_task_runner_ = new base::TestSimpleTaskRunner(); -} - -void ExternalPolicyDataUpdaterTest::CreateUpdater(size_t max_parallel_fetches) { - fetcher_backend_.reset(new ExternalPolicyDataFetcherBackend( - io_task_runner_, - scoped_refptr<net::URLRequestContextGetter>())); - updater_.reset(new ExternalPolicyDataUpdater( - backend_task_runner_, - fetcher_backend_->CreateFrontend(backend_task_runner_), - max_parallel_fetches)); -} - -void ExternalPolicyDataUpdaterTest::RequestExternalDataFetch(int key_index, - int url_index) { - updater_->FetchExternalData( - kExternalPolicyDataKeys[key_index], - CreateRequest(kExternalPolicyDataURLs[url_index]), - callback_listener_.CreateCallback(kExternalPolicyDataKeys[key_index])); - io_task_runner_->RunUntilIdle(); - backend_task_runner_->RunPendingTasks(); -} - -void ExternalPolicyDataUpdaterTest::RequestExternalDataFetch(int index) { - RequestExternalDataFetch(index, index); -} - -ExternalPolicyDataUpdater::Request - ExternalPolicyDataUpdaterTest::CreateRequest(const std::string& url) const { - return ExternalPolicyDataUpdater::Request( - url, - base::SHA1HashString(kExternalPolicyDataPayload), - kExternalPolicyDataMaxSize); -} - -TEST_F(ExternalPolicyDataUpdaterTest, FetchSuccess) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the second fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the first fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[0], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, PayloadSizeExceedsLimit) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the second fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Indicate that the payload size will exceed allowed maximum. - fetcher->delegate()->OnURLFetchDownloadProgress( - fetcher, - kExternalPolicyDataMaxSize + 1, - -1); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that a retry has been scheduled for the first fetch. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, FetchFailure) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the second fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the first fetch fail due to an interrupted connection. - fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_NETWORK_CHANGED)); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that a retry has been scheduled for the first fetch. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, ServerFailure) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the second fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the first fetch fail with a server error. - fetcher->set_response_code(500); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that a retry has been scheduled for the first fetch. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, RetryLimit) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make a fetch request. - RequestExternalDataFetch(0); - - int fetcher_id = 0; - - // Verify that client failures cause the fetch to be retried three times. - for (int i = 0; i < 3; ++i) { - // Verify that the fetch has been (re)started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(fetcher_id); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail with a client error. - fetcher->set_response_code(400); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(fetcher_id)); - - // Verify that a retry has been scheduled. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); - - // Fast-forward time to the scheduled retry. - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); - ++fetcher_id; - } - - // Verify that the fetch has been restarted. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(fetcher_id); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail once more. - fetcher->set_response_code(400); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - ++fetcher_id; - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(fetcher_id)); - - // Verify that no further retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, RetryWithBackoff) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make a fetch request. - RequestExternalDataFetch(0); - - base::TimeDelta expected_delay = base::TimeDelta::FromSeconds(60); - const base::TimeDelta delay_cap = base::TimeDelta::FromHours(12); - - int fetcher_id = 0; - - // The backoff delay is capped at 12 hours, which is reached after 10 retries: - // 60 * 2^10 == 61440 > 43200 == 12 * 60 * 60 - for (int i = 0; i < 20; ++i) { - // Verify that the fetch has been (re)started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(fetcher_id); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the fetch fail with a server error. - fetcher->set_response_code(500); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(fetcher_id)); - - // Verify that a retry has been scheduled. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); - - // Verify that the retry delay has been doubled, with random jitter from 80% - // to 100%. - const base::TestPendingTask& task = - backend_task_runner_->GetPendingTasks().front(); - EXPECT_GT(task.delay, - base::TimeDelta::FromMilliseconds( - 0.799 * expected_delay.InMilliseconds())); - EXPECT_LE(task.delay, expected_delay); - - if (i < 10) { - // The delay cap has not been reached yet. - EXPECT_LT(expected_delay, delay_cap); - expected_delay *= 2; - - if (i == 9) { - // The last doubling reached the cap. - EXPECT_GT(expected_delay, delay_cap); - expected_delay = delay_cap; - } - } - - // Fast-forward time to the scheduled retry. - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); - ++fetcher_id; - } -} - -TEST_F(ExternalPolicyDataUpdaterTest, HashInvalid) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the second fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the first fetch retrieve data whose hash does not match the expected - // value. - fetcher->set_response_code(200); - fetcher->SetResponseString("Invalid external policy data"); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that a retry has been scheduled for the first fetch. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, DataRejectedByCallback) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make a fetch request. - RequestExternalDataFetch(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Reject the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[0], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(false)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that a retry has been scheduled. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); - - // Fast-forward time to the scheduled retry. - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); - - // Verify that the fetch has been restarted. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked this time. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[0], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, URLChanged) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make a fetch request. - RequestExternalDataFetch(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make another fetch request with the same key but an updated URL. - RequestExternalDataFetch(0, 1); - - // Verify that the original fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that a new fetch has been started with the updated URL. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, JobInvalidated) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the second fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make another fetch request with the same key as the second request but an - // updated URL. - RequestExternalDataFetch(1, 2); - - // Verify that the first fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Verify that the second fetch has still not been started. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Make the first fetch fail with a server error. - fetcher->set_response_code(500); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the second fetch was invalidated and the third fetch has been - // started instead. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, FetchCanceled) { - // Create an updater that runs one fetch at a time. - CreateUpdater(1); - - // Make a fetch request. - RequestExternalDataFetch(0); - - // Verify that the fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Cancel the fetch request. - updater_->CancelExternalDataFetch(kExternalPolicyDataKeys[0]); - io_task_runner_->RunUntilIdle(); - backend_task_runner_->RunPendingTasks(); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, ParallelJobs) { - // Create an updater that runs up to two fetches in parallel. - CreateUpdater(2); - - // Make three fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - RequestExternalDataFetch(2); - - // Verify that the third fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that the second fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that the first fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the first fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[0], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the third fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Verify that the second fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Complete the second fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[1], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the third fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Complete the third fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[2], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the third fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, ParallelJobsFinishingOutOfOrder) { - // Create an updater that runs up to two fetches in parallel. - CreateUpdater(2); - - // Make three fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - RequestExternalDataFetch(2); - - // Verify that the third fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Complete the second fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[1], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the third fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Verify that the first fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Complete the first fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[0], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the third fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Complete the third fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[2], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the third fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, ParallelJobsWithRetry) { - // Create an updater that runs up to two fetches in parallel. - CreateUpdater(2); - - // Make three fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - RequestExternalDataFetch(2); - - // Verify that the third fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that the second fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that the first fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Make the first fetch fail with a client error. - fetcher->set_response_code(400); - fetcher->delegate()->OnURLFetchComplete(fetcher); - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - - // Verify that the first fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the third fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Verify that a retry has been scheduled for the first fetch. - EXPECT_EQ(1u, backend_task_runner_->GetPendingTasks().size()); - - // Fast-forward time to the scheduled retry. - backend_task_runner_->RunPendingTasks(); - io_task_runner_->RunUntilIdle(); - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); - - // Verify that the first fetch has not been restarted yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(3)); - - // Complete the third fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[2], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the third fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that the second fetch is still running - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that the first fetch has been restarted. - fetcher = fetcher_factory_.GetFetcherByID(3); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Verify that no further retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, ParallelJobsWithCancel) { - // Create an updater that runs up to two fetches in parallel. - CreateUpdater(2); - - // Make three fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - RequestExternalDataFetch(2); - - // Verify that the third fetch has not been started yet. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that the second fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Verify that the first fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Cancel the fetch request. - updater_->CancelExternalDataFetch(kExternalPolicyDataKeys[0]); - io_task_runner_->RunUntilIdle(); - backend_task_runner_->RunPendingTasks(); - - // Verify that the fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(0)); - - // Verify that the third fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Verify that the second fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Complete the second fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[1], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the third fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); - - // Complete the third fetch. - fetcher->set_response_code(200); - fetcher->SetResponseString(kExternalPolicyDataPayload); - fetcher->delegate()->OnURLFetchComplete(fetcher); - - // Accept the data when the callback is invoked. - EXPECT_CALL(callback_listener_, - OnFetchSuccess(kExternalPolicyDataKeys[2], - kExternalPolicyDataPayload)) - .Times(1) - .WillOnce(Return(true)); - backend_task_runner_->RunPendingTasks(); - Mock::VerifyAndClearExpectations(&callback_listener_); - io_task_runner_->RunUntilIdle(); - - // Verify that the third fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(2)); - - // Verify that no retries have been scheduled. - EXPECT_TRUE(backend_task_runner_->GetPendingTasks().empty()); -} - -TEST_F(ExternalPolicyDataUpdaterTest, ParallelJobsWithInvalidatedJob) { - // Create an updater that runs up to two fetches in parallel. - CreateUpdater(2); - - // Make two fetch requests. - RequestExternalDataFetch(0); - RequestExternalDataFetch(1); - - // Verify that the first fetch has been started. - net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Verify that the second fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(1); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[1]), fetcher->GetOriginalURL()); - - // Make another fetch request with the same key as the second request but an - // updated URL. - RequestExternalDataFetch(1, 2); - - // Verify that the first fetch is still running. - fetcher = fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[0]), fetcher->GetOriginalURL()); - - // Verify that the second fetch is no longer running. - EXPECT_FALSE(fetcher_factory_.GetFetcherByID(1)); - - // Verify that the third fetch has been started. - fetcher = fetcher_factory_.GetFetcherByID(2); - ASSERT_TRUE(fetcher); - EXPECT_EQ(GURL(kExternalPolicyDataURLs[2]), fetcher->GetOriginalURL()); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/message_util.cc b/chrome/browser/policy/cloud/message_util.cc deleted file mode 100644 index fca7a9f..0000000 --- a/chrome/browser/policy/cloud/message_util.cc +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/message_util.h" - -#include "base/logging.h" -#include "grit/component_strings.h" -#include "ui/base/l10n/l10n_util.h" - -namespace policy { - -namespace { - -int GetIDSForDMStatus(DeviceManagementStatus status) { - switch (status) { - case DM_STATUS_SUCCESS: - return IDS_POLICY_DM_STATUS_SUCCESS; - case DM_STATUS_REQUEST_INVALID: - return IDS_POLICY_DM_STATUS_REQUEST_INVALID; - case DM_STATUS_REQUEST_FAILED: - return IDS_POLICY_DM_STATUS_REQUEST_FAILED; - case DM_STATUS_TEMPORARY_UNAVAILABLE: - return IDS_POLICY_DM_STATUS_TEMPORARY_UNAVAILABLE; - case DM_STATUS_HTTP_STATUS_ERROR: - return IDS_POLICY_DM_STATUS_HTTP_STATUS_ERROR; - case DM_STATUS_RESPONSE_DECODING_ERROR: - return IDS_POLICY_DM_STATUS_RESPONSE_DECODING_ERROR; - case DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED: - return IDS_POLICY_DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED; - case DM_STATUS_SERVICE_DEVICE_NOT_FOUND: - return IDS_POLICY_DM_STATUS_SERVICE_DEVICE_NOT_FOUND; - case DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID: - return IDS_POLICY_DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID; - case DM_STATUS_SERVICE_ACTIVATION_PENDING: - return IDS_POLICY_DM_STATUS_SERVICE_ACTIVATION_PENDING; - case DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER: - return IDS_POLICY_DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER; - case DM_STATUS_SERVICE_DEVICE_ID_CONFLICT: - return IDS_POLICY_DM_STATUS_SERVICE_DEVICE_ID_CONFLICT; - case DM_STATUS_SERVICE_MISSING_LICENSES: - return IDS_POLICY_DM_STATUS_SERVICE_MISSING_LICENSES; - case DM_STATUS_SERVICE_POLICY_NOT_FOUND: - return IDS_POLICY_DM_STATUS_SERVICE_POLICY_NOT_FOUND; - } - NOTREACHED() << "Unhandled DM status " << status; - return IDS_POLICY_DM_STATUS_UNKNOWN_ERROR; -} - -int GetIDSForValidationStatus(CloudPolicyValidatorBase::Status status) { - switch (status) { - case CloudPolicyValidatorBase::VALIDATION_OK: - return IDS_POLICY_VALIDATION_OK; - case CloudPolicyValidatorBase::VALIDATION_BAD_INITIAL_SIGNATURE: - return IDS_POLICY_VALIDATION_BAD_INITIAL_SIGNATURE; - case CloudPolicyValidatorBase::VALIDATION_BAD_SIGNATURE: - return IDS_POLICY_VALIDATION_BAD_SIGNATURE; - case CloudPolicyValidatorBase::VALIDATION_ERROR_CODE_PRESENT: - return IDS_POLICY_VALIDATION_ERROR_CODE_PRESENT; - case CloudPolicyValidatorBase::VALIDATION_PAYLOAD_PARSE_ERROR: - return IDS_POLICY_VALIDATION_PAYLOAD_PARSE_ERROR; - case CloudPolicyValidatorBase::VALIDATION_WRONG_POLICY_TYPE: - return IDS_POLICY_VALIDATION_WRONG_POLICY_TYPE; - case CloudPolicyValidatorBase::VALIDATION_WRONG_SETTINGS_ENTITY_ID: - return IDS_POLICY_VALIDATION_WRONG_SETTINGS_ENTITY_ID; - case CloudPolicyValidatorBase::VALIDATION_BAD_TIMESTAMP: - return IDS_POLICY_VALIDATION_BAD_TIMESTAMP; - case CloudPolicyValidatorBase::VALIDATION_WRONG_TOKEN: - return IDS_POLICY_VALIDATION_WRONG_TOKEN; - case CloudPolicyValidatorBase::VALIDATION_BAD_USERNAME: - return IDS_POLICY_VALIDATION_BAD_USERNAME; - case CloudPolicyValidatorBase::VALIDATION_POLICY_PARSE_ERROR: - return IDS_POLICY_VALIDATION_POLICY_PARSE_ERROR; - } - NOTREACHED() << "Unhandled validation status " << status; - return IDS_POLICY_VALIDATION_UNKNOWN_ERROR; -} - -int GetIDSForStoreStatus(CloudPolicyStore::Status status) { - switch (status) { - case CloudPolicyStore::STATUS_OK: - return IDS_POLICY_STORE_STATUS_OK; - case CloudPolicyStore::STATUS_LOAD_ERROR: - return IDS_POLICY_STORE_STATUS_LOAD_ERROR; - case CloudPolicyStore::STATUS_STORE_ERROR: - return IDS_POLICY_STORE_STATUS_STORE_ERROR; - case CloudPolicyStore::STATUS_PARSE_ERROR: - return IDS_POLICY_STORE_STATUS_PARSE_ERROR; - case CloudPolicyStore::STATUS_SERIALIZE_ERROR: - return IDS_POLICY_STORE_STATUS_SERIALIZE_ERROR; - case CloudPolicyStore::STATUS_VALIDATION_ERROR: - // This is handled separately below to include the validation error. - break; - case CloudPolicyStore::STATUS_BAD_STATE: - return IDS_POLICY_STORE_STATUS_BAD_STATE; - } - NOTREACHED() << "Unhandled store status " << status; - return IDS_POLICY_STORE_STATUS_UNKNOWN_ERROR; -} - -} // namespace - -string16 FormatDeviceManagementStatus(DeviceManagementStatus status) { - return l10n_util::GetStringUTF16(GetIDSForDMStatus(status)); -} - -string16 FormatValidationStatus( - CloudPolicyValidatorBase::Status validation_status) { - return l10n_util::GetStringUTF16( - GetIDSForValidationStatus(validation_status)); -} - -string16 FormatStoreStatus(CloudPolicyStore::Status store_status, - CloudPolicyValidatorBase::Status validation_status) { - if (store_status == CloudPolicyStore::STATUS_VALIDATION_ERROR) { - return l10n_util::GetStringFUTF16( - IDS_POLICY_STORE_STATUS_VALIDATION_ERROR, - l10n_util::GetStringUTF16( - GetIDSForValidationStatus(validation_status))); - } - - return l10n_util::GetStringUTF16(GetIDSForStoreStatus(store_status)); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/message_util.h b/chrome/browser/policy/cloud/message_util.h deleted file mode 100644 index 324cf70..0000000 --- a/chrome/browser/policy/cloud/message_util.h +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_MESSAGE_UTIL_H_ -#define CHROME_BROWSER_POLICY_CLOUD_MESSAGE_UTIL_H_ - -#include "base/strings/string16.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" - -namespace policy { - -// Returns a string describing |status| suitable for display in UI. -string16 FormatDeviceManagementStatus(DeviceManagementStatus status); - -// Returns a string describing |validation_status| suitable for display in UI. -string16 FormatValidationStatus( - CloudPolicyValidatorBase::Status validation_status); - -// Returns a textual description of |store_status| for display in the UI. If -// |store_status| is STATUS_VALIDATION_FAILED, |validation_status| will be -// consulted to create a description of the validation failure. -string16 FormatStoreStatus(CloudPolicyStore::Status store_status, - CloudPolicyValidatorBase::Status validation_status); - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_MESSAGE_UTIL_H_ diff --git a/chrome/browser/policy/cloud/mock_cloud_external_data_manager.cc b/chrome/browser/policy/cloud/mock_cloud_external_data_manager.cc deleted file mode 100644 index d1b0c16..0000000 --- a/chrome/browser/policy/cloud/mock_cloud_external_data_manager.cc +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/mock_cloud_external_data_manager.h" - -#include "base/callback.h" -#include "base/memory/weak_ptr.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "net/url_request/url_request_context_getter.h" - -namespace policy { - -MockCloudExternalDataManager::MockCloudExternalDataManager() { -} - -MockCloudExternalDataManager::~MockCloudExternalDataManager() { -} - -scoped_ptr<ExternalDataFetcher> - MockCloudExternalDataManager::CreateExternalDataFetcher( - const std::string& policy) { - return make_scoped_ptr(new ExternalDataFetcher(weak_factory_.GetWeakPtr(), - policy)); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/mock_cloud_external_data_manager.h b/chrome/browser/policy/cloud/mock_cloud_external_data_manager.h deleted file mode 100644 index c1e3c10..0000000 --- a/chrome/browser/policy/cloud/mock_cloud_external_data_manager.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_EXTERNAL_DATA_MANAGER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_EXTERNAL_DATA_MANAGER_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace net { -class URLRequestContextGetter; -} - -namespace policy { - -class ExternalDataFetcher; - -class MockCloudExternalDataManager : public CloudExternalDataManager { - public: - MockCloudExternalDataManager(); - virtual ~MockCloudExternalDataManager(); - - MOCK_METHOD0(OnPolicyStoreLoaded, void(void)); - MOCK_METHOD1(Connect, void(scoped_refptr<net::URLRequestContextGetter>)); - MOCK_METHOD0(Disconnect, void(void)); - MOCK_METHOD2(Fetch, void(const std::string&, - const ExternalDataFetcher::FetchCallback&)); - - scoped_ptr<ExternalDataFetcher> CreateExternalDataFetcher( - const std::string& policy); - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudExternalDataManager); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_EXTERNAL_DATA_MANAGER_H_ diff --git a/chrome/browser/policy/cloud/mock_cloud_policy_client.cc b/chrome/browser/policy/cloud/mock_cloud_policy_client.cc deleted file mode 100644 index 12d8648..0000000 --- a/chrome/browser/policy/cloud/mock_cloud_policy_client.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "net/url_request/url_request_context_getter.h" - -namespace em = enterprise_management; - -namespace policy { - -MockCloudPolicyClient::MockCloudPolicyClient() - : CloudPolicyClient(std::string(), - std::string(), - USER_AFFILIATION_NONE, - NULL, - NULL, - NULL) {} - -MockCloudPolicyClient::~MockCloudPolicyClient() {} - -void MockCloudPolicyClient::SetDMToken(const std::string& token) { - dm_token_ = token; -} - -void MockCloudPolicyClient::SetPolicy(const PolicyNamespaceKey& policy_ns_key, - const em::PolicyFetchResponse& policy) { - em::PolicyFetchResponse*& response = responses_[policy_ns_key]; - delete response; - response = new enterprise_management::PolicyFetchResponse(policy); -} - -void MockCloudPolicyClient::SetStatus(DeviceManagementStatus status) { - status_ = status; -} - -MockCloudPolicyClientObserver::MockCloudPolicyClientObserver() {} - -MockCloudPolicyClientObserver::~MockCloudPolicyClientObserver() {} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/mock_cloud_policy_client.h b/chrome/browser/policy/cloud/mock_cloud_policy_client.h deleted file mode 100644 index db9aca9..0000000 --- a/chrome/browser/policy/cloud/mock_cloud_policy_client.h +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_POLICY_CLIENT_H_ -#define CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_POLICY_CLIENT_H_ - -#include <string> - -#include "base/basictypes.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace policy { - -class MockCloudPolicyClient : public CloudPolicyClient { - public: - MockCloudPolicyClient(); - virtual ~MockCloudPolicyClient(); - - MOCK_METHOD2(SetupRegistration, void(const std::string&, const std::string&)); - MOCK_METHOD5(Register, void( - enterprise_management::DeviceRegisterRequest::Type type, - const std::string&, const std::string&, bool, const std::string&)); - MOCK_METHOD0(FetchPolicy, void(void)); - MOCK_METHOD0(Unregister, void(void)); - MOCK_METHOD2(UploadCertificate, - void(const std::string&, const StatusCallback&)); - - // Sets the DMToken. - void SetDMToken(const std::string& token); - - // Injects policy. - void SetPolicy(const PolicyNamespaceKey& policy_ns_key, - const enterprise_management::PolicyFetchResponse& policy); - - // Sets the status field. - void SetStatus(DeviceManagementStatus status); - - // Make the notification helpers public. - using CloudPolicyClient::NotifyPolicyFetched; - using CloudPolicyClient::NotifyRegistrationStateChanged; - using CloudPolicyClient::NotifyClientError; - - using CloudPolicyClient::dm_token_; - using CloudPolicyClient::client_id_; - using CloudPolicyClient::submit_machine_id_; - using CloudPolicyClient::last_policy_timestamp_; - using CloudPolicyClient::public_key_version_; - using CloudPolicyClient::public_key_version_valid_; - using CloudPolicyClient::namespaces_to_fetch_; - using CloudPolicyClient::invalidation_version_; - using CloudPolicyClient::invalidation_payload_; - using CloudPolicyClient::fetched_invalidation_version_; - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudPolicyClient); -}; - -class MockCloudPolicyClientObserver : public CloudPolicyClient::Observer { - public: - MockCloudPolicyClientObserver(); - virtual ~MockCloudPolicyClientObserver(); - - MOCK_METHOD1(OnPolicyFetched, void(CloudPolicyClient*)); - MOCK_METHOD1(OnRegistrationStateChanged, void(CloudPolicyClient*)); - MOCK_METHOD1(OnRobotAuthCodesFetched, void(CloudPolicyClient*)); - MOCK_METHOD1(OnClientError, void(CloudPolicyClient*)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudPolicyClientObserver); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_POLICY_CLIENT_H_ diff --git a/chrome/browser/policy/cloud/mock_cloud_policy_store.cc b/chrome/browser/policy/cloud/mock_cloud_policy_store.cc deleted file mode 100644 index 8c2fb3b..0000000 --- a/chrome/browser/policy/cloud/mock_cloud_policy_store.cc +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" - -namespace policy { - -MockCloudPolicyStore::MockCloudPolicyStore() {} - -MockCloudPolicyStore::~MockCloudPolicyStore() {} - -MockCloudPolicyStoreObserver::MockCloudPolicyStoreObserver() {} - -MockCloudPolicyStoreObserver::~MockCloudPolicyStoreObserver() {} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/mock_cloud_policy_store.h b/chrome/browser/policy/cloud/mock_cloud_policy_store.h deleted file mode 100644 index 684f37c..0000000 --- a/chrome/browser/policy/cloud/mock_cloud_policy_store.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_POLICY_STORE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_POLICY_STORE_H_ - -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace policy { - -class MockCloudPolicyStore : public CloudPolicyStore { - public: - MockCloudPolicyStore(); - virtual ~MockCloudPolicyStore(); - - MOCK_METHOD1(Store, void(const enterprise_management::PolicyFetchResponse&)); - MOCK_METHOD0(Load, void(void)); - - // Publish the protected members. - using CloudPolicyStore::NotifyStoreLoaded; - using CloudPolicyStore::NotifyStoreError; - - using CloudPolicyStore::policy_map_; - using CloudPolicyStore::policy_; - using CloudPolicyStore::status_; - using CloudPolicyStore::invalidation_version_; - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudPolicyStore); -}; - -class MockCloudPolicyStoreObserver : public CloudPolicyStore::Observer { - public: - MockCloudPolicyStoreObserver(); - virtual ~MockCloudPolicyStoreObserver(); - - MOCK_METHOD1(OnStoreLoaded, void(CloudPolicyStore* store)); - MOCK_METHOD1(OnStoreError, void(CloudPolicyStore* store)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudPolicyStoreObserver); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_MOCK_CLOUD_POLICY_STORE_H_ diff --git a/chrome/browser/policy/cloud/mock_device_management_service.cc b/chrome/browser/policy/cloud/mock_device_management_service.cc deleted file mode 100644 index 6f51b3f..0000000 --- a/chrome/browser/policy/cloud/mock_device_management_service.cc +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/mock_device_management_service.h" - -#include "base/strings/string_util.h" -#include "net/base/net_errors.h" -#include "net/url_request/url_request_context_getter.h" - -using testing::Action; - -namespace em = enterprise_management; - -namespace policy { -namespace { - -const char kServerUrl[] = "https://example.com/management_service"; -const char kUserAgent[] = "Chrome 1.2.3(456)"; -const char kPlatform[] = "Test|Unit|1.2.3"; - -// Common mock request job functionality. -class MockRequestJobBase : public DeviceManagementRequestJob { - public: - MockRequestJobBase(JobType type, - MockDeviceManagementService* service) - : DeviceManagementRequestJob(type, std::string(), std::string()), - service_(service) {} - virtual ~MockRequestJobBase() {} - - protected: - virtual void Run() OVERRIDE { - service_->StartJob(ExtractParameter(dm_protocol::kParamRequest), - gaia_token_, - ExtractParameter(dm_protocol::kParamOAuthToken), - dm_token_, - ExtractParameter(dm_protocol::kParamUserAffiliation), - ExtractParameter(dm_protocol::kParamDeviceID), - request_); - } - - private: - // Searches for a query parameter and returns the associated value. - const std::string& ExtractParameter(const std::string& name) const { - for (ParameterMap::const_iterator entry(query_params_.begin()); - entry != query_params_.end(); - ++entry) { - if (name == entry->first) - return entry->second; - } - - return base::EmptyString(); - } - - MockDeviceManagementService* service_; - - DISALLOW_COPY_AND_ASSIGN(MockRequestJobBase); -}; - -// Synchronous mock request job that immediately completes on calling Run(). -class SyncRequestJob : public MockRequestJobBase { - public: - SyncRequestJob(JobType type, - MockDeviceManagementService* service, - DeviceManagementStatus status, - const em::DeviceManagementResponse& response) - : MockRequestJobBase(type, service), - status_(status), - response_(response) {} - virtual ~SyncRequestJob() {} - - protected: - virtual void Run() OVERRIDE { - MockRequestJobBase::Run(); - callback_.Run(status_, net::OK, response_); - } - - private: - DeviceManagementStatus status_; - em::DeviceManagementResponse response_; - - DISALLOW_COPY_AND_ASSIGN(SyncRequestJob); -}; - -// Asynchronous job that allows the test to delay job completion. -class AsyncRequestJob : public MockRequestJobBase, - public MockDeviceManagementJob { - public: - AsyncRequestJob(JobType type, MockDeviceManagementService* service) - : MockRequestJobBase(type, service) {} - virtual ~AsyncRequestJob() {} - - protected: - virtual void RetryJob() OVERRIDE { - if (!retry_callback_.is_null()) - retry_callback_.Run(this); - Run(); - } - - virtual void SendResponse( - DeviceManagementStatus status, - const em::DeviceManagementResponse& response) OVERRIDE { - callback_.Run(status, net::OK, response); - } - - private: - DISALLOW_COPY_AND_ASSIGN(AsyncRequestJob); -}; - -} // namespace - -ACTION_P3(CreateSyncMockDeviceManagementJob, service, status, response) { - return new SyncRequestJob(arg0, service, status, response); -} - -ACTION_P2(CreateAsyncMockDeviceManagementJob, service, mock_job) { - AsyncRequestJob* job = new AsyncRequestJob(arg0, service); - *mock_job = job; - return job; -} - -MockDeviceManagementJob::~MockDeviceManagementJob() {} - -MockDeviceManagementServiceConfiguration:: - MockDeviceManagementServiceConfiguration() - : server_url_(kServerUrl) {} - -MockDeviceManagementServiceConfiguration:: - MockDeviceManagementServiceConfiguration(const std::string& server_url) - : server_url_(server_url) {} - -MockDeviceManagementServiceConfiguration:: - ~MockDeviceManagementServiceConfiguration() {} - -std::string MockDeviceManagementServiceConfiguration::GetServerUrl() { - return server_url_; -} - -std::string MockDeviceManagementServiceConfiguration::GetAgentParameter() { - return kUserAgent; -} - -std::string MockDeviceManagementServiceConfiguration::GetPlatformParameter() { - return kPlatform; -} - -MockDeviceManagementService::MockDeviceManagementService() - : DeviceManagementService(scoped_ptr<Configuration>( - new MockDeviceManagementServiceConfiguration)) {} - -MockDeviceManagementService::~MockDeviceManagementService() {} - -Action<MockDeviceManagementService::CreateJobFunction> - MockDeviceManagementService::SucceedJob( - const em::DeviceManagementResponse& response) { - return CreateSyncMockDeviceManagementJob(this, DM_STATUS_SUCCESS, response); -} - -Action<MockDeviceManagementService::CreateJobFunction> - MockDeviceManagementService::FailJob(DeviceManagementStatus status) { - const em::DeviceManagementResponse dummy_response; - return CreateSyncMockDeviceManagementJob(this, status, dummy_response); -} - -Action<MockDeviceManagementService::CreateJobFunction> - MockDeviceManagementService::CreateAsyncJob(MockDeviceManagementJob** job) { - return CreateAsyncMockDeviceManagementJob(this, job); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/mock_device_management_service.h b/chrome/browser/policy/cloud/mock_device_management_service.h deleted file mode 100644 index c992c55f7..0000000 --- a/chrome/browser/policy/cloud/mock_device_management_service.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_MOCK_DEVICE_MANAGEMENT_SERVICE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_MOCK_DEVICE_MANAGEMENT_SERVICE_H_ - -#include <string> - -#include "base/basictypes.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace policy { - -class MockDeviceManagementJob { - public: - virtual ~MockDeviceManagementJob(); - virtual void RetryJob() = 0; - virtual void SendResponse( - DeviceManagementStatus status, - const enterprise_management::DeviceManagementResponse& response) = 0; -}; - -class MockDeviceManagementServiceConfiguration - : public DeviceManagementService::Configuration { - public: - MockDeviceManagementServiceConfiguration(); - explicit MockDeviceManagementServiceConfiguration( - const std::string& server_url); - virtual ~MockDeviceManagementServiceConfiguration(); - - virtual std::string GetServerUrl() OVERRIDE; - virtual std::string GetAgentParameter() OVERRIDE; - virtual std::string GetPlatformParameter() OVERRIDE; - - private: - const std::string server_url_; - - DISALLOW_COPY_AND_ASSIGN(MockDeviceManagementServiceConfiguration); -}; - -class MockDeviceManagementService : public DeviceManagementService { - public: - MockDeviceManagementService(); - virtual ~MockDeviceManagementService(); - - typedef DeviceManagementRequestJob* CreateJobFunction( - DeviceManagementRequestJob::JobType, net::URLRequestContextGetter*); - - MOCK_METHOD2(CreateJob, CreateJobFunction); - MOCK_METHOD7( - StartJob, - void(const std::string& request_type, - const std::string& gaia_token, - const std::string& oauth_token, - const std::string& dm_token, - const std::string& user_affiliation, - const std::string& client_id, - const enterprise_management::DeviceManagementRequest& request)); - - // Creates a gmock action that will make the job succeed. - testing::Action<CreateJobFunction> SucceedJob( - const enterprise_management::DeviceManagementResponse& response); - - // Creates a gmock action which will fail the job with the given error. - testing::Action<CreateJobFunction> FailJob(DeviceManagementStatus status); - - // Creates a gmock action which will capture the job so the test code can - // delay job completion. - testing::Action<CreateJobFunction> CreateAsyncJob( - MockDeviceManagementJob** job); - - private: - DISALLOW_COPY_AND_ASSIGN(MockDeviceManagementService); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_MOCK_DEVICE_MANAGEMENT_SERVICE_H_ diff --git a/chrome/browser/policy/cloud/policy_builder.cc b/chrome/browser/policy/cloud/policy_builder.cc deleted file mode 100644 index 28fad08..0000000 --- a/chrome/browser/policy/cloud/policy_builder.cc +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/policy_builder.h" - -#include <vector> - -#include "base/stl_util.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "crypto/signature_creator.h" -#include "policy/proto/cloud_policy.pb.h" - -namespace em = enterprise_management; - -namespace policy { - -namespace { - -// Signing key test data in DER-encoded PKCS8 format. -const uint8 kSigningKey[] = { - 0x30, 0x82, 0x01, 0x55, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, - 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, - 0x01, 0x3f, 0x30, 0x82, 0x01, 0x3b, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00, - 0xd9, 0xcd, 0xca, 0xcd, 0xc3, 0xea, 0xbe, 0x72, 0x79, 0x1c, 0x29, 0x37, - 0x39, 0x99, 0x1f, 0xd4, 0xb3, 0x0e, 0xf0, 0x7b, 0x78, 0x77, 0x0e, 0x05, - 0x3b, 0x65, 0x34, 0x12, 0x62, 0xaf, 0xa6, 0x8d, 0x33, 0xce, 0x78, 0xf8, - 0x47, 0x05, 0x1d, 0x98, 0xaa, 0x1b, 0x1f, 0x50, 0x05, 0x5b, 0x3c, 0x19, - 0x3f, 0x80, 0x83, 0x63, 0x63, 0x3a, 0xec, 0xcb, 0x2e, 0x90, 0x4f, 0xf5, - 0x26, 0x76, 0xf1, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x40, 0x64, - 0x29, 0xc2, 0xd9, 0x6b, 0xfe, 0xf9, 0x84, 0x75, 0x73, 0xe0, 0xf4, 0x77, - 0xb5, 0x96, 0xb0, 0xdf, 0x83, 0xc0, 0x4e, 0x57, 0xf1, 0x10, 0x6e, 0x91, - 0x89, 0x12, 0x30, 0x5e, 0x57, 0xff, 0x14, 0x59, 0x5f, 0x18, 0x86, 0x4e, - 0x4b, 0x17, 0x56, 0xfc, 0x8d, 0x40, 0xdd, 0x74, 0x65, 0xd3, 0xff, 0x67, - 0x64, 0xcb, 0x9c, 0xb4, 0x14, 0x8a, 0x06, 0xb7, 0x13, 0x45, 0x94, 0x16, - 0x7d, 0x3f, 0xe1, 0x02, 0x21, 0x00, 0xf6, 0x0f, 0x31, 0x6d, 0x06, 0xcc, - 0x3b, 0xa0, 0x44, 0x1f, 0xf5, 0xc2, 0x45, 0x2b, 0x10, 0x6c, 0xf9, 0x6f, - 0x8f, 0x87, 0x3d, 0xc0, 0x3b, 0x55, 0x13, 0x37, 0x80, 0xcd, 0x9f, 0xe1, - 0xb7, 0xd9, 0x02, 0x21, 0x00, 0xe2, 0x9a, 0x5f, 0xbf, 0x95, 0x74, 0xb5, - 0x7a, 0x6a, 0xa6, 0x97, 0xbd, 0x75, 0x8c, 0x97, 0x18, 0x24, 0xd6, 0x09, - 0xcd, 0xdc, 0xb5, 0x94, 0xbf, 0xe2, 0x78, 0xaa, 0x20, 0x47, 0x9f, 0x68, - 0x5d, 0x02, 0x21, 0x00, 0xaf, 0x8f, 0x97, 0x8c, 0x5a, 0xd5, 0x4d, 0x95, - 0xc4, 0x05, 0xa9, 0xab, 0xba, 0xfe, 0x46, 0xf1, 0xf9, 0xe7, 0x07, 0x59, - 0x4f, 0x4d, 0xe1, 0x07, 0x8a, 0x76, 0x87, 0x88, 0x2f, 0x13, 0x35, 0xc1, - 0x02, 0x20, 0x24, 0xc3, 0xd9, 0x2f, 0x13, 0x47, 0x99, 0x3e, 0x20, 0x59, - 0xa1, 0x1a, 0xeb, 0x1c, 0x81, 0x53, 0x38, 0x7e, 0xc5, 0x9e, 0x71, 0xe5, - 0xc0, 0x19, 0x95, 0xdb, 0xef, 0xf6, 0x46, 0xc8, 0x95, 0x3d, 0x02, 0x21, - 0x00, 0xaa, 0xb1, 0xff, 0x8a, 0xa2, 0xb2, 0x2b, 0xef, 0x9a, 0x83, 0x3f, - 0xc5, 0xbc, 0xd4, 0x6a, 0x07, 0xe8, 0xc7, 0x0b, 0x2e, 0xd4, 0x0f, 0xf8, - 0x98, 0x68, 0xe1, 0x04, 0xa8, 0x92, 0xd0, 0x10, 0xaa, -}; - -// New signing key test data in DER-encoded PKCS8 format. -const uint8 kNewSigningKey[] = { - 0x30, 0x82, 0x01, 0x54, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, - 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, - 0x01, 0x3e, 0x30, 0x82, 0x01, 0x3a, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00, - 0x99, 0x98, 0x6b, 0x79, 0x5d, 0x38, 0x33, 0x79, 0x27, 0x0a, 0x2e, 0xb0, - 0x89, 0xba, 0xf8, 0xf6, 0x80, 0xde, 0xb0, 0x79, 0xf2, 0xd4, 0x6d, 0xf7, - 0x3c, 0xa3, 0x97, 0xf6, 0x4a, 0x3c, 0xa5, 0xcc, 0x40, 0x8a, 0xef, 0x59, - 0xaa, 0xc2, 0x82, 0x8f, 0xbc, 0x0d, 0x5b, 0x63, 0xc6, 0xaa, 0x72, 0xe2, - 0xf3, 0x57, 0xdd, 0x74, 0x00, 0xb0, 0x42, 0xd6, 0x27, 0xe7, 0x17, 0x61, - 0x0a, 0xdc, 0xc1, 0xf7, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x40, 0x34, - 0xcf, 0xc9, 0xb4, 0x73, 0x2f, 0x0d, 0xd3, 0xcc, 0x6e, 0x9d, 0xdb, 0x29, - 0xa0, 0x56, 0x56, 0x3b, 0xbd, 0x56, 0x24, 0xb8, 0x2f, 0xfe, 0x97, 0x92, - 0x0c, 0x16, 0x06, 0x23, 0x44, 0x73, 0x25, 0x1d, 0x65, 0xf4, 0xda, 0x77, - 0xe7, 0x91, 0x2e, 0x91, 0x05, 0x10, 0xc1, 0x1b, 0x39, 0x5e, 0xb2, 0xf7, - 0xbd, 0x14, 0x19, 0xcb, 0x6b, 0xc3, 0xa9, 0xe8, 0x91, 0xf7, 0xa7, 0xa9, - 0x90, 0x08, 0x51, 0x02, 0x21, 0x00, 0xcc, 0x9e, 0x03, 0x54, 0x8f, 0x24, - 0xde, 0x90, 0x25, 0xec, 0x21, 0xaf, 0xe6, 0x27, 0x2a, 0x16, 0x42, 0x74, - 0xda, 0xf8, 0x84, 0xc4, 0x8c, 0x1e, 0x86, 0x12, 0x04, 0x5c, 0x17, 0x01, - 0xea, 0x9d, 0x02, 0x21, 0x00, 0xc0, 0x2a, 0x6c, 0xe9, 0xa1, 0x1a, 0x41, - 0x11, 0x94, 0x50, 0xf7, 0x1a, 0xd3, 0xbc, 0xf3, 0xa2, 0xf8, 0x46, 0xbc, - 0x26, 0x77, 0x78, 0xef, 0xc0, 0x54, 0xec, 0x22, 0x3f, 0x2c, 0x57, 0xe0, - 0xa3, 0x02, 0x20, 0x31, 0xf2, 0xc8, 0xa1, 0x55, 0xa8, 0x0c, 0x64, 0x67, - 0xbd, 0x72, 0xa3, 0xbb, 0xad, 0x07, 0xcb, 0x13, 0x41, 0xef, 0x4a, 0x07, - 0x2e, 0xeb, 0x7d, 0x70, 0x00, 0xe9, 0xeb, 0x88, 0xfa, 0x40, 0xc9, 0x02, - 0x20, 0x3a, 0xe0, 0xc4, 0xde, 0x10, 0x6e, 0x6a, 0xe1, 0x68, 0x00, 0x26, - 0xb6, 0x21, 0x8a, 0x13, 0x5c, 0x2b, 0x96, 0x00, 0xb0, 0x08, 0x8b, 0x15, - 0x6a, 0x68, 0x9a, 0xb1, 0x23, 0x8a, 0x02, 0xa2, 0xe1, 0x02, 0x21, 0x00, - 0xa3, 0xf2, 0x2d, 0x55, 0xc1, 0x6d, 0x40, 0xfa, 0x1d, 0xf7, 0xba, 0x86, - 0xef, 0x50, 0x98, 0xfc, 0xee, 0x09, 0xcc, 0xe7, 0x22, 0xb9, 0x4e, 0x80, - 0x32, 0x1a, 0x6b, 0xb3, 0x5f, 0x35, 0xbd, 0xf3, -}; - -} // namespace - -// Constants used as dummy data for filling the PolicyData protobuf. -const char PolicyBuilder::kFakeDeviceId[] = "device-id"; -const char PolicyBuilder::kFakeDomain[] = "example.com"; -const char PolicyBuilder::kFakeMachineName[] = "machine-name"; -const char PolicyBuilder::kFakePolicyType[] = "policy type"; -const int PolicyBuilder::kFakePublicKeyVersion = 17; -const int64 PolicyBuilder::kFakeTimestamp = 365LL * 24 * 60 * 60 * 1000; -const char PolicyBuilder::kFakeToken[] = "token"; -const char PolicyBuilder::kFakeUsername[] = "username@example.com"; -const char PolicyBuilder::kFakeServiceAccountIdentity[] = "robot4test@g.com"; - -PolicyBuilder::PolicyBuilder() - : policy_data_(new em::PolicyData()) { - SetDefaultSigningKey(); - policy_data_->set_policy_type(kFakePolicyType); - policy_data_->set_timestamp(kFakeTimestamp); - policy_data_->set_request_token(kFakeToken); - policy_data_->set_machine_name(kFakeMachineName); - policy_data_->set_public_key_version(kFakePublicKeyVersion); - policy_data_->set_username(kFakeUsername); - policy_data_->set_device_id(kFakeDeviceId); - policy_data_->set_state(em::PolicyData::ACTIVE); - policy_data_->set_service_account_identity(kFakeServiceAccountIdentity); -} - -PolicyBuilder::~PolicyBuilder() {} - -scoped_ptr<crypto::RSAPrivateKey> PolicyBuilder::GetSigningKey() { - if (raw_signing_key_.empty()) - return scoped_ptr<crypto::RSAPrivateKey>(); - return scoped_ptr<crypto::RSAPrivateKey>( - crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(raw_signing_key_)); -} - -void PolicyBuilder::SetSigningKey(const crypto::RSAPrivateKey& key) { - key.ExportPrivateKey(&raw_signing_key_); -} - -void PolicyBuilder::SetDefaultSigningKey() { - std::vector<uint8> key(kSigningKey, kSigningKey + arraysize(kSigningKey)); - raw_signing_key_.swap(key); -} - -void PolicyBuilder::UnsetSigningKey() { - raw_signing_key_.clear(); -} - -scoped_ptr<crypto::RSAPrivateKey> PolicyBuilder::GetNewSigningKey() { - if (raw_new_signing_key_.empty()) - return scoped_ptr<crypto::RSAPrivateKey>(); - return scoped_ptr<crypto::RSAPrivateKey>( - crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(raw_new_signing_key_)); -} - -void PolicyBuilder::SetDefaultNewSigningKey() { - std::vector<uint8> key(kNewSigningKey, - kNewSigningKey + arraysize(kNewSigningKey)); - raw_new_signing_key_.swap(key); -} - -void PolicyBuilder::UnsetNewSigningKey() { - raw_new_signing_key_.clear(); -} - -void PolicyBuilder::Build() { - if (policy_data_.get()) - CHECK(policy_data_->SerializeToString(policy_.mutable_policy_data())); - - // Generate signatures if applicable. - scoped_ptr<crypto::RSAPrivateKey> policy_signing_key = GetNewSigningKey(); - if (policy_signing_key) { - // Add the new public key. - std::vector<uint8> raw_new_public_signing_key; - CHECK(policy_signing_key->ExportPublicKey(&raw_new_public_signing_key)); - policy_.set_new_public_key(vector_as_array(&raw_new_public_signing_key), - raw_new_public_signing_key.size()); - - // The new public key must be signed by the old key. - scoped_ptr<crypto::RSAPrivateKey> old_signing_key = GetSigningKey(); - if (old_signing_key) { - SignData(policy_.new_public_key(), - old_signing_key.get(), - policy_.mutable_new_public_key_signature()); - } - } else { - policy_signing_key = GetSigningKey(); - } - - // PolicyData signature. - if (policy_signing_key) { - SignData(policy_.policy_data(), policy_signing_key.get(), - policy_.mutable_policy_data_signature()); - } -} - -std::string PolicyBuilder::GetBlob() { - return policy_.SerializeAsString(); -} - -scoped_ptr<em::PolicyFetchResponse> PolicyBuilder::GetCopy() { - scoped_ptr<em::PolicyFetchResponse> result(new em::PolicyFetchResponse()); - result->CopyFrom(policy_); - return result.Pass(); -} - -// static -scoped_ptr<crypto::RSAPrivateKey> PolicyBuilder::CreateTestSigningKey() { - std::vector<uint8> raw_signing_key( - kSigningKey, kSigningKey + arraysize(kSigningKey)); - return scoped_ptr<crypto::RSAPrivateKey>( - crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(raw_signing_key)); -} - -// static -scoped_ptr<crypto::RSAPrivateKey> PolicyBuilder::CreateTestOtherSigningKey() { - std::vector<uint8> raw_new_signing_key( - kNewSigningKey, kNewSigningKey + arraysize(kNewSigningKey)); - return scoped_ptr<crypto::RSAPrivateKey>( - crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(raw_new_signing_key)); -} - -void PolicyBuilder::SignData(const std::string& data, - crypto::RSAPrivateKey* key, - std::string* signature) { - scoped_ptr<crypto::SignatureCreator> signature_creator( - crypto::SignatureCreator::Create(key)); - signature_creator->Update(reinterpret_cast<const uint8*>(data.c_str()), - data.size()); - std::vector<uint8> signature_bytes; - CHECK(signature_creator->Final(&signature_bytes)); - signature->assign( - reinterpret_cast<const char*>(vector_as_array(&signature_bytes)), - signature_bytes.size()); -} - -template<> -TypedPolicyBuilder<em::CloudPolicySettings>::TypedPolicyBuilder() - : payload_(new em::CloudPolicySettings()) { - policy_data().set_policy_type(dm_protocol::kChromeUserPolicyType); -} - -template<> -TypedPolicyBuilder<em::ExternalPolicyData>::TypedPolicyBuilder() - : payload_(new em::ExternalPolicyData()) { - policy_data().set_policy_type(dm_protocol::kChromeExtensionPolicyType); -} - - -// Have the instantiations compiled into the module. -template class TypedPolicyBuilder<em::CloudPolicySettings>; -template class TypedPolicyBuilder<em::ExternalPolicyData>; - -} // namespace policy diff --git a/chrome/browser/policy/cloud/policy_builder.h b/chrome/browser/policy/cloud/policy_builder.h deleted file mode 100644 index 5f3b530..0000000 --- a/chrome/browser/policy/cloud/policy_builder.h +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_POLICY_BUILDER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_POLICY_BUILDER_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/proto/cloud/chrome_extension_policy.pb.h" -#include "chrome/browser/policy/proto/cloud/device_management_local.pb.h" -#include "crypto/rsa_private_key.h" -#include "policy/proto/cloud_policy.pb.h" - -namespace policy { - -// A helper class for testing that provides a straightforward interface for -// constructing policy blobs for use in testing. NB: This uses fake data and -// hard-coded signing keys by default, so should not be used in production code. -class PolicyBuilder { - public: - // Constants used as dummy data for filling the PolicyData protobuf. - static const char kFakeDeviceId[]; - static const char kFakeDomain[]; - static const char kFakeMachineName[]; - static const char kFakePolicyType[]; - static const int kFakePublicKeyVersion; - static const int64 kFakeTimestamp; - static const char kFakeToken[]; - static const char kFakeUsername[]; - static const char kFakeServiceAccountIdentity[]; - - // Creates a policy builder. The builder will have all PolicyData fields - // initialized to dummy values and use the test signing keys. - PolicyBuilder(); - virtual ~PolicyBuilder(); - - // Use this member to access the PolicyData protobuf. - enterprise_management::PolicyData& policy_data() { - if (!policy_data_.get()) - policy_data_.reset(new enterprise_management::PolicyData()); - return *policy_data_; - } - void clear_policy_data() { - policy_data_.reset(); - } - - enterprise_management::PolicyFetchResponse& policy() { - return policy_; - } - - scoped_ptr<crypto::RSAPrivateKey> GetSigningKey(); - void SetSigningKey(const crypto::RSAPrivateKey& key); - void SetDefaultSigningKey(); - void UnsetSigningKey(); - - scoped_ptr<crypto::RSAPrivateKey> GetNewSigningKey(); - void SetDefaultNewSigningKey(); - void UnsetNewSigningKey(); - - // Assembles the policy components. The resulting policy protobuf is available - // through policy() after this call. - virtual void Build(); - - // Returns a copy of policy(). - scoped_ptr<enterprise_management::PolicyFetchResponse> GetCopy(); - - // Returns a binary policy blob, i.e. an encoded PolicyFetchResponse. - std::string GetBlob(); - - // These return hard-coded testing keys. Don't use in production! - static scoped_ptr<crypto::RSAPrivateKey> CreateTestSigningKey(); - static scoped_ptr<crypto::RSAPrivateKey> CreateTestOtherSigningKey(); - - private: - // Produces |key|'s signature over |data| and stores it in |signature|. - void SignData(const std::string& data, - crypto::RSAPrivateKey* key, - std::string* signature); - - enterprise_management::PolicyFetchResponse policy_; - scoped_ptr<enterprise_management::PolicyData> policy_data_; - std::string payload_data_; - - // The keys cannot be stored in NSS. Temporary keys are not guaranteed to - // remain in the database. Persistent keys require a persistent database, - // which would coincide with the user's database. However, these keys are used - // for signing the policy and don't have to coincide with the user's known - // keys. Instead, we store the private keys as raw bytes. Where needed, a - // temporary RSAPrivateKey is created. - std::vector<uint8> raw_signing_key_; - std::vector<uint8> raw_new_signing_key_; - - DISALLOW_COPY_AND_ASSIGN(PolicyBuilder); -}; - -// Type-parameterized PolicyBuilder extension that allows for building policy -// blobs carrying protobuf payloads. -template<typename PayloadProto> -class TypedPolicyBuilder : public PolicyBuilder { - public: - TypedPolicyBuilder(); - virtual ~TypedPolicyBuilder() {} - - // Returns a reference to the payload protobuf being built. - PayloadProto& payload() { - if (!payload_.get()) - payload_.reset(new PayloadProto()); - return *payload_; - } - void clear_payload() { - payload_.reset(); - } - - // PolicyBuilder: - virtual void Build() OVERRIDE { - if (payload_.get()) - CHECK(payload_->SerializeToString(policy_data().mutable_policy_value())); - - PolicyBuilder::Build(); - } - - private: - scoped_ptr<PayloadProto> payload_; - - DISALLOW_COPY_AND_ASSIGN(TypedPolicyBuilder); -}; - -typedef TypedPolicyBuilder<enterprise_management::CloudPolicySettings> - UserPolicyBuilder; -typedef TypedPolicyBuilder<enterprise_management::ExternalPolicyData> - ComponentPolicyBuilder; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_POLICY_BUILDER_H_ diff --git a/chrome/browser/policy/cloud/rate_limiter.cc b/chrome/browser/policy/cloud/rate_limiter.cc deleted file mode 100644 index b0992a6..0000000 --- a/chrome/browser/policy/cloud/rate_limiter.cc +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/rate_limiter.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/sequenced_task_runner.h" -#include "base/time/tick_clock.h" - -namespace policy { - -RateLimiter::RateLimiter(size_t max_requests, - const base::TimeDelta& duration, - const base::Closure& callback, - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_ptr<base::TickClock> clock) - : max_requests_(max_requests), - duration_(duration), - callback_(callback), - task_runner_(task_runner), - clock_(clock.Pass()) { - DCHECK_GT(max_requests_, 0u); -} - -RateLimiter::~RateLimiter() {} - -void RateLimiter::PostRequest() { - DCHECK(CalledOnValidThread()); - - const base::TimeTicks now = clock_->NowTicks(); - const base::TimeTicks period_start = now - duration_; - while (!invocation_times_.empty() && - invocation_times_.front() <= period_start) { - invocation_times_.pop(); - } - - delayed_callback_.Cancel(); - - if (invocation_times_.size() < max_requests_) { - invocation_times_.push(now); - callback_.Run(); - } else { - // From the while() loop above we have front() > period_start, - // so time_until_next_callback > 0. - const base::TimeDelta time_until_next_callback = - invocation_times_.front() - period_start; - delayed_callback_.Reset( - base::Bind(&RateLimiter::PostRequest, base::Unretained(this))); - task_runner_->PostDelayedTask( - FROM_HERE, delayed_callback_.callback(), time_until_next_callback); - } -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/rate_limiter.h b/chrome/browser/policy/cloud/rate_limiter.h deleted file mode 100644 index 00af48d..0000000 --- a/chrome/browser/policy/cloud/rate_limiter.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_RATE_LIMITER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_RATE_LIMITER_H_ - -#include <queue> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/cancelable_callback.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/threading/non_thread_safe.h" -#include "base/time/time.h" - -namespace base { -class SequencedTaskRunner; -class TickClock; -} - -namespace policy { - -// A simple class to limit the rate at which a callback is invoked. -class RateLimiter : public base::NonThreadSafe { - public: - // Will limit invocations of |callback| to |max_requests| per |duration|. - // |task_runner| is used to post delayed tasks, and |clock| is used to - // measure elapsed time. - RateLimiter(size_t max_requests, - const base::TimeDelta& duration, - const base::Closure& callback, - scoped_refptr<base::SequencedTaskRunner> task_runner, - scoped_ptr<base::TickClock> clock); - ~RateLimiter(); - - // Posts a request to invoke |callback_|. It is invoked immediately if the - // rate in the preceding |duration_| period is within the limit, otherwise - // the callback will be invoked later, ensuring the allowed rate is not - // exceeded. - void PostRequest(); - - private: - const size_t max_requests_; - const base::TimeDelta duration_; - base::Closure callback_; - scoped_refptr<base::SequencedTaskRunner> task_runner_; - scoped_ptr<base::TickClock> clock_; - - std::queue<base::TimeTicks> invocation_times_; - base::CancelableClosure delayed_callback_; - - DISALLOW_COPY_AND_ASSIGN(RateLimiter); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_RATE_LIMITER_H_ diff --git a/chrome/browser/policy/cloud/rate_limiter_unittest.cc b/chrome/browser/policy/cloud/rate_limiter_unittest.cc deleted file mode 100644 index 18995aa..0000000 --- a/chrome/browser/policy/cloud/rate_limiter_unittest.cc +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/rate_limiter.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/test/simple_test_tick_clock.h" -#include "base/test/test_simple_task_runner.h" -#include "base/time/tick_clock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { - -class RateLimiterTest : public testing::Test { - public: - RateLimiterTest() - : task_runner_(new base::TestSimpleTaskRunner()), - clock_(new base::SimpleTestTickClock()), - callbacks_(0), - max_requests_(5), - duration_(base::TimeDelta::FromHours(1)), - small_delta_(base::TimeDelta::FromMinutes(1)), - limiter_(max_requests_, - duration_, - base::Bind(&RateLimiterTest::Callback, base::Unretained(this)), - task_runner_, - scoped_ptr<base::TickClock>(clock_).Pass()) {} - virtual ~RateLimiterTest() {} - - protected: - void Callback() { - callbacks_++; - } - - scoped_refptr<base::TestSimpleTaskRunner> task_runner_; - base::SimpleTestTickClock* clock_; - size_t callbacks_; - const size_t max_requests_; - const base::TimeDelta duration_; - const base::TimeDelta small_delta_; - RateLimiter limiter_; -}; - -TEST_F(RateLimiterTest, LimitRequests) { - size_t count = 0; - for (size_t i = 0; i < max_requests_; ++i) { - EXPECT_EQ(count, callbacks_); - limiter_.PostRequest(); - ++count; - EXPECT_EQ(count, callbacks_); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); - clock_->Advance(small_delta_); - } - - for (size_t i = 0; i < 10; ++i) { - limiter_.PostRequest(); - EXPECT_EQ(max_requests_, callbacks_); - clock_->Advance(small_delta_); - EXPECT_FALSE(task_runner_->GetPendingTasks().empty()); - } - - // Now advance the clock beyond the duration. The callback is invoked once. - callbacks_ = 0; - clock_->Advance(duration_); - task_runner_->RunPendingTasks(); - EXPECT_EQ(1u, callbacks_); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); -} - -TEST_F(RateLimiterTest, Steady) { - const base::TimeDelta delta = duration_ / 2; - size_t count = 0; - for (int i = 0; i < 100; ++i) { - EXPECT_EQ(count, callbacks_); - limiter_.PostRequest(); - ++count; - EXPECT_EQ(count, callbacks_); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); - clock_->Advance(delta); - } -} - -TEST_F(RateLimiterTest, RetryAfterDelay) { - size_t count = 0; - base::TimeDelta total_delta; - // Fill the queue. - for (size_t i = 0; i < max_requests_; ++i) { - EXPECT_EQ(count, callbacks_); - limiter_.PostRequest(); - ++count; - EXPECT_EQ(count, callbacks_); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); - clock_->Advance(small_delta_); - total_delta += small_delta_; - } - - // Now post a request that will be delayed. - EXPECT_EQ(max_requests_, callbacks_); - limiter_.PostRequest(); - EXPECT_EQ(max_requests_, callbacks_); - EXPECT_FALSE(task_runner_->GetPendingTasks().empty()); - - while (total_delta < duration_) { - task_runner_->RunPendingTasks(); - // The queue is still full, so another task is immediately posted. - EXPECT_FALSE(task_runner_->GetPendingTasks().empty()); - clock_->Advance(small_delta_); - total_delta += small_delta_; - } - - // Now advance time beyond the initial duration. It will immediately execute - // the callback. - EXPECT_EQ(max_requests_, callbacks_); - task_runner_->RunPendingTasks(); - EXPECT_TRUE(task_runner_->GetPendingTasks().empty()); - EXPECT_EQ(max_requests_ + 1, callbacks_); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/resource_cache.cc b/chrome/browser/policy/cloud/resource_cache.cc deleted file mode 100644 index 0ee7e3a..0000000 --- a/chrome/browser/policy/cloud/resource_cache.cc +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/resource_cache.h" - -#include "base/base64.h" -#include "base/callback.h" -#include "base/file_util.h" -#include "base/files/file_enumerator.h" -#include "base/logging.h" -#include "base/safe_numerics.h" -#include "base/sequenced_task_runner.h" -#include "base/strings/string_util.h" - -namespace policy { - -namespace { - -// Verifies that |value| is not empty and encodes it into base64url format, -// which is safe to use as a file name on all platforms. -bool Base64Encode(const std::string& value, std::string* encoded) { - DCHECK(!value.empty()); - if (value.empty() || !base::Base64Encode(value, encoded)) - return false; - base::ReplaceChars(*encoded, "+", "-", encoded); - base::ReplaceChars(*encoded, "/", "_", encoded); - return true; -} - -// Decodes all elements of |input| from base64url format and stores the decoded -// elements in |output|. -bool Base64Encode(const std::set<std::string>& input, - std::set<std::string>* output) { - output->clear(); - for (std::set<std::string>::const_iterator it = input.begin(); - it != input.end(); ++it) { - std::string encoded; - if (!Base64Encode(*it, &encoded)) { - output->clear(); - return false; - } - output->insert(encoded); - } - return true; -} - -// Decodes |encoded| from base64url format and verifies that the result is not -// emtpy. -bool Base64Decode(const std::string& encoded, std::string* value) { - std::string buffer; - base::ReplaceChars(encoded, "-", "+", &buffer); - base::ReplaceChars(buffer, "_", "/", &buffer); - return base::Base64Decode(buffer, value) && !value->empty(); -} - -} // namespace - -ResourceCache::ResourceCache( - const base::FilePath& cache_dir, - scoped_refptr<base::SequencedTaskRunner> task_runner) - : cache_dir_(cache_dir), - task_runner_(task_runner) { -} - -ResourceCache::~ResourceCache() { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); -} - -bool ResourceCache::Store(const std::string& key, - const std::string& subkey, - const std::string& data) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - base::FilePath subkey_path; - // Delete the file before writing to it. This ensures that the write does not - // follow a symlink planted at |subkey_path|, clobbering a file outside the - // cache directory. The mechanism is meant to foil file-system-level attacks - // where a symlink is planted in the cache directory before Chrome has - // started. An attacker controlling a process running concurrently with Chrome - // would be able to race against the protection by re-creating the symlink - // between these two calls. There is nothing in file_util that could be used - // to protect against such races, especially as the cache is cross-platform - // and therefore cannot use any POSIX-only tricks. - int size = base::checked_numeric_cast<int>(data.size()); - return VerifyKeyPathAndGetSubkeyPath(key, true, subkey, &subkey_path) && - base::DeleteFile(subkey_path, false) && - (file_util::WriteFile(subkey_path, data.data(), size) == size); -} - -bool ResourceCache::Load(const std::string& key, - const std::string& subkey, - std::string* data) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - base::FilePath subkey_path; - // Only read from |subkey_path| if it is not a symlink. - if (!VerifyKeyPathAndGetSubkeyPath(key, false, subkey, &subkey_path) || - base::IsLink(subkey_path)) { - return false; - } - data->clear(); - return base::ReadFileToString(subkey_path, data); -} - -void ResourceCache::LoadAllSubkeys( - const std::string& key, - std::map<std::string, std::string>* contents) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - contents->clear(); - base::FilePath key_path; - if (!VerifyKeyPath(key, false, &key_path)) - return; - - base::FileEnumerator enumerator(key_path, false, base::FileEnumerator::FILES); - for (base::FilePath path = enumerator.Next(); !path.empty(); - path = enumerator.Next()) { - const std::string encoded_subkey = path.BaseName().MaybeAsASCII(); - std::string subkey; - std::string data; - // Only read from |subkey_path| if it is not a symlink and its name is - // a base64-encoded string. - if (!base::IsLink(path) && - Base64Decode(encoded_subkey, &subkey) && - base::ReadFileToString(path, &data)) { - (*contents)[subkey].swap(data); - } - } -} - -void ResourceCache::Delete(const std::string& key, const std::string& subkey) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - base::FilePath subkey_path; - if (VerifyKeyPathAndGetSubkeyPath(key, false, subkey, &subkey_path)) - base::DeleteFile(subkey_path, false); - // Delete() does nothing if the directory given to it is not empty. Hence, the - // call below deletes the directory representing |key| if its last subkey was - // just removed and does nothing otherwise. - base::DeleteFile(subkey_path.DirName(), false); -} - -void ResourceCache::Clear(const std::string& key) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - base::FilePath key_path; - if (VerifyKeyPath(key, false, &key_path)) - base::DeleteFile(key_path, true); -} - -void ResourceCache::FilterSubkeys(const std::string& key, - const SubkeyFilter& test) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - - base::FilePath key_path; - if (!VerifyKeyPath(key, false, &key_path)) - return; - - base::FileEnumerator enumerator(key_path, false, base::FileEnumerator::FILES); - for (base::FilePath subkey_path = enumerator.Next(); - !subkey_path.empty(); subkey_path = enumerator.Next()) { - std::string subkey; - // Delete files with invalid names, and files whose subkey doesn't pass the - // filter. - if (!Base64Decode(subkey_path.BaseName().MaybeAsASCII(), &subkey) || - test.Run(subkey)) { - base::DeleteFile(subkey_path, true); - } - } - - // Delete() does nothing if the directory given to it is not empty. Hence, the - // call below deletes the directory representing |key| if all of its subkeys - // were just removed and does nothing otherwise. - base::DeleteFile(key_path, false); -} - -void ResourceCache::PurgeOtherKeys(const std::set<std::string>& keys_to_keep) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - std::set<std::string> encoded_keys_to_keep; - if (!Base64Encode(keys_to_keep, &encoded_keys_to_keep)) - return; - - base::FileEnumerator enumerator( - cache_dir_, false, base::FileEnumerator::DIRECTORIES); - for (base::FilePath path = enumerator.Next(); !path.empty(); - path = enumerator.Next()) { - const std::string name(path.BaseName().MaybeAsASCII()); - if (encoded_keys_to_keep.find(name) == encoded_keys_to_keep.end()) - base::DeleteFile(path, true); - } -} - -void ResourceCache::PurgeOtherSubkeys( - const std::string& key, - const std::set<std::string>& subkeys_to_keep) { - DCHECK(task_runner_->RunsTasksOnCurrentThread()); - base::FilePath key_path; - if (!VerifyKeyPath(key, false, &key_path)) - return; - - std::set<std::string> encoded_subkeys_to_keep; - if (!Base64Encode(subkeys_to_keep, &encoded_subkeys_to_keep)) - return; - - base::FileEnumerator enumerator(key_path, false, base::FileEnumerator::FILES); - for (base::FilePath path = enumerator.Next(); !path.empty(); - path = enumerator.Next()) { - const std::string name(path.BaseName().MaybeAsASCII()); - if (encoded_subkeys_to_keep.find(name) == encoded_subkeys_to_keep.end()) - base::DeleteFile(path, false); - } - // Delete() does nothing if the directory given to it is not empty. Hence, the - // call below deletes the directory representing |key| if all of its subkeys - // were just removed and does nothing otherwise. - base::DeleteFile(key_path, false); -} - -bool ResourceCache::VerifyKeyPath(const std::string& key, - bool allow_create, - base::FilePath* path) { - std::string encoded; - if (!Base64Encode(key, &encoded)) - return false; - *path = cache_dir_.AppendASCII(encoded); - return allow_create ? base::CreateDirectory(*path) : - base::DirectoryExists(*path); -} - -bool ResourceCache::VerifyKeyPathAndGetSubkeyPath(const std::string& key, - bool allow_create_key, - const std::string& subkey, - base::FilePath* path) { - base::FilePath key_path; - std::string encoded; - if (!VerifyKeyPath(key, allow_create_key, &key_path) || - !Base64Encode(subkey, &encoded)) { - return false; - } - *path = key_path.AppendASCII(encoded); - return true; -} - - -} // namespace policy diff --git a/chrome/browser/policy/cloud/resource_cache.h b/chrome/browser/policy/cloud/resource_cache.h deleted file mode 100644 index 1519a45..0000000 --- a/chrome/browser/policy/cloud/resource_cache.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_RESOURCE_CACHE_H_ -#define CHROME_BROWSER_POLICY_CLOUD_RESOURCE_CACHE_H_ - -#include <map> -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/callback_forward.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace policy { - -// Manages storage of data at a given path. The data is keyed by a key and -// a subkey, and can be queried by (key, subkey) or (key) lookups. -// The contents of the cache have to be manually cleared using Delete() or -// Purge*(). -// The class can be instantiated on any thread but from then on, it must be -// accessed via the |task_runner| only. The |task_runner| must support file I/O. -class ResourceCache { - public: - explicit ResourceCache(const base::FilePath& cache_path, - scoped_refptr<base::SequencedTaskRunner> task_runner); - virtual ~ResourceCache(); - - // Stores |data| under (key, subkey). Returns true if the store suceeded, and - // false otherwise. - bool Store(const std::string& key, - const std::string& subkey, - const std::string& data); - - // Loads the contents of (key, subkey) into |data| and returns true. Returns - // false if (key, subkey) isn't found or if there is a problem reading the - // data. - bool Load(const std::string& key, - const std::string& subkey, - std::string* data); - - // Loads all the subkeys of |key| into |contents|. - void LoadAllSubkeys(const std::string& key, - std::map<std::string, std::string>* contents); - - // Deletes (key, subkey). - void Delete(const std::string& key, const std::string& subkey); - - // Deletes all the subkeys of |key|. - void Clear(const std::string& key); - - // Deletes the subkeys of |key| for which the |filter| returns true. - typedef base::Callback<bool(const std::string&)> SubkeyFilter; - void FilterSubkeys(const std::string& key, const SubkeyFilter& filter); - - // Deletes all keys not in |keys_to_keep|, along with their subkeys. - void PurgeOtherKeys(const std::set<std::string>& keys_to_keep); - - // Deletes all the subkeys of |key| not in |subkeys_to_keep|. - void PurgeOtherSubkeys(const std::string& key, - const std::set<std::string>& subkeys_to_keep); - - private: - // Points |path| at the cache directory for |key| and returns whether the - // directory exists. If |allow_create| is |true|, the directory is created if - // it did not exist yet. - bool VerifyKeyPath(const std::string& key, - bool allow_create, - base::FilePath* path); - - // Points |path| at the file in which data for (key, subkey) should be stored - // and returns whether the parent directory of this file exists. If - // |allow_create_key| is |true|, the directory is created if it did not exist - // yet. This method does not check whether the file at |path| exists or not. - bool VerifyKeyPathAndGetSubkeyPath(const std::string& key, - bool allow_create_key, - const std::string& subkey, - base::FilePath* subkey_path); - - base::FilePath cache_dir_; - - // Task runner that |this| runs on. - scoped_refptr<base::SequencedTaskRunner> task_runner_; - - DISALLOW_COPY_AND_ASSIGN(ResourceCache); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_RESOURCE_CACHE_H_ diff --git a/chrome/browser/policy/cloud/resource_cache_unittest.cc b/chrome/browser/policy/cloud/resource_cache_unittest.cc deleted file mode 100644 index afca625..0000000 --- a/chrome/browser/policy/cloud/resource_cache_unittest.cc +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/resource_cache.h" - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/callback.h" -#include "base/files/scoped_temp_dir.h" -#include "base/test/test_simple_task_runner.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { - -namespace { - -const char kKey1[] = "key 1"; -const char kKey2[] = "key 2"; -const char kKey3[] = "key 3"; -const char kSubA[] = "a"; -const char kSubB[] = "bb"; -const char kSubC[] = "ccc"; -const char kSubD[] = "dddd"; -const char kSubE[] = "eeeee"; - -const char kData0[] = "{ \"key\": \"value\" }"; -const char kData1[] = "{}"; - -bool Matches(const std::string& expected, const std::string& subkey) { - return subkey == expected; -} - -} // namespace - -TEST(ResourceCacheTest, StoreAndLoad) { - base::ScopedTempDir temp_dir; - ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - ResourceCache cache(temp_dir.path(), - make_scoped_refptr(new base::TestSimpleTaskRunner)); - - // No data initially. - std::string data; - EXPECT_FALSE(cache.Load(kKey1, kSubA, &data)); - - // Store some data and load it. - EXPECT_TRUE(cache.Store(kKey1, kSubA, kData0)); - EXPECT_TRUE(cache.Load(kKey1, kSubA, &data)); - EXPECT_EQ(kData0, data); - - // Store more data in another subkey. - EXPECT_TRUE(cache.Store(kKey1, kSubB, kData1)); - - // Write subkeys to two other keys. - EXPECT_TRUE(cache.Store(kKey2, kSubA, kData0)); - EXPECT_TRUE(cache.Store(kKey2, kSubB, kData1)); - EXPECT_TRUE(cache.Store(kKey3, kSubA, kData0)); - EXPECT_TRUE(cache.Store(kKey3, kSubB, kData1)); - - // Enumerate all the subkeys. - std::map<std::string, std::string> contents; - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(2u, contents.size()); - EXPECT_EQ(kData0, contents[kSubA]); - EXPECT_EQ(kData1, contents[kSubB]); - - // Store more subkeys. - EXPECT_TRUE(cache.Store(kKey1, kSubC, kData1)); - EXPECT_TRUE(cache.Store(kKey1, kSubD, kData1)); - EXPECT_TRUE(cache.Store(kKey1, kSubE, kData1)); - - // Now purge some of them. - std::set<std::string> keep; - keep.insert(kSubB); - keep.insert(kSubD); - cache.PurgeOtherSubkeys(kKey1, keep); - - // Enumerate all the remaining subkeys. - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(2u, contents.size()); - EXPECT_EQ(kData1, contents[kSubB]); - EXPECT_EQ(kData1, contents[kSubD]); - - // Delete subkeys directly. - cache.Delete(kKey1, kSubB); - cache.Delete(kKey1, kSubD); - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(0u, contents.size()); - - // The other two keys were not affected. - cache.LoadAllSubkeys(kKey2, &contents); - EXPECT_EQ(2u, contents.size()); - EXPECT_EQ(kData0, contents[kSubA]); - EXPECT_EQ(kData1, contents[kSubB]); - cache.LoadAllSubkeys(kKey3, &contents); - EXPECT_EQ(2u, contents.size()); - EXPECT_EQ(kData0, contents[kSubA]); - EXPECT_EQ(kData1, contents[kSubB]); - - // Now purge all keys except the third. - keep.clear(); - keep.insert(kKey3); - cache.PurgeOtherKeys(keep); - - // The first two keys are empty. - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(0u, contents.size()); - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(0u, contents.size()); - - // The third key is unaffected. - cache.LoadAllSubkeys(kKey3, &contents); - EXPECT_EQ(2u, contents.size()); - EXPECT_EQ(kData0, contents[kSubA]); - EXPECT_EQ(kData1, contents[kSubB]); -} - -TEST(ResourceCacheTest, FilterSubkeys) { - base::ScopedTempDir temp_dir; - ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); - ResourceCache cache(temp_dir.path(), - make_scoped_refptr(new base::TestSimpleTaskRunner)); - - // Store some data. - EXPECT_TRUE(cache.Store(kKey1, kSubA, kData0)); - EXPECT_TRUE(cache.Store(kKey1, kSubB, kData1)); - EXPECT_TRUE(cache.Store(kKey1, kSubC, kData0)); - EXPECT_TRUE(cache.Store(kKey2, kSubA, kData0)); - EXPECT_TRUE(cache.Store(kKey2, kSubB, kData1)); - EXPECT_TRUE(cache.Store(kKey3, kSubA, kData0)); - EXPECT_TRUE(cache.Store(kKey3, kSubB, kData1)); - - // Check the contents of kKey1. - std::map<std::string, std::string> contents; - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(3u, contents.size()); - EXPECT_EQ(kData0, contents[kSubA]); - EXPECT_EQ(kData1, contents[kSubB]); - EXPECT_EQ(kData0, contents[kSubC]); - - // Filter some subkeys. - cache.FilterSubkeys(kKey1, base::Bind(&Matches, kSubA)); - - // Check the contents of kKey1 again. - cache.LoadAllSubkeys(kKey1, &contents); - EXPECT_EQ(2u, contents.size()); - EXPECT_EQ(kData1, contents[kSubB]); - EXPECT_EQ(kData0, contents[kSubC]); - - // Other keys weren't affected. - cache.LoadAllSubkeys(kKey2, &contents); - EXPECT_EQ(2u, contents.size()); - cache.LoadAllSubkeys(kKey3, &contents); - EXPECT_EQ(2u, contents.size()); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/system_policy_request_context.cc b/chrome/browser/policy/cloud/system_policy_request_context.cc deleted file mode 100644 index 7e8a442..0000000 --- a/chrome/browser/policy/cloud/system_policy_request_context.cc +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/system_policy_request_context.h" - -#include "base/logging.h" -#include "base/single_thread_task_runner.h" -#include "net/cookies/cookie_monster.h" -#include "net/http/http_network_layer.h" -#include "net/url_request/url_request_context.h" - -namespace policy { - -SystemPolicyRequestContext::SystemPolicyRequestContext( - scoped_refptr<net::URLRequestContextGetter> system_context_getter, - const std::string& user_agent) - : system_context_getter_(system_context_getter), - http_user_agent_settings_("*", user_agent) { - DCHECK(system_context_getter); -} - -SystemPolicyRequestContext::~SystemPolicyRequestContext() { -} - -net::URLRequestContext* -SystemPolicyRequestContext::GetURLRequestContext() { - DCHECK(GetNetworkTaskRunner()->RunsTasksOnCurrentThread()); - if (!context_.get()) { - // Create our URLRequestContext(). - context_.reset(new net::URLRequestContext()); - - net::URLRequestContext* system_context = - system_context_getter_->GetURLRequestContext(); - // Share resolver, proxy service and ssl bits with the system context. - // This is important so we don't make redundant requests (e.g. when - // resolving proxy auto configuration). - // TODO(atwilson): Consider using CopyFrom() here to copy all services - - // http://crbug.com/322422. - context_->set_net_log(system_context->net_log()); - context_->set_host_resolver(system_context->host_resolver()); - context_->set_proxy_service(system_context->proxy_service()); - context_->set_ssl_config_service( - system_context->ssl_config_service()); - - // Set our custom UserAgent. - context_->set_http_user_agent_settings(&http_user_agent_settings_); - - // Share the http session. - http_transaction_factory_.reset(new net::HttpNetworkLayer( - system_context->http_transaction_factory()->GetSession())); - context_->set_http_transaction_factory(http_transaction_factory_.get()); - - // No cookies, please. We also don't track channel IDs (no - // ServerBoundCertService). - context_->set_cookie_store(new net::CookieMonster(NULL, NULL)); - } - - return context_.get(); -} - -scoped_refptr<base::SingleThreadTaskRunner> -SystemPolicyRequestContext::GetNetworkTaskRunner() const { - return system_context_getter_->GetNetworkTaskRunner(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/system_policy_request_context.h b/chrome/browser/policy/cloud/system_policy_request_context.h deleted file mode 100644 index 186f2b4..0000000 --- a/chrome/browser/policy/cloud/system_policy_request_context.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/scoped_ptr.h" -#include "net/url_request/static_http_user_agent_settings.h" -#include "net/url_request/url_request_context_getter.h" - -#ifndef CHROME_BROWSER_POLICY_CLOUD_SYSTEM_POLICY_REQUEST_CONTEXT_H_ -#define CHROME_BROWSER_POLICY_CLOUD_SYSTEM_POLICY_REQUEST_CONTEXT_H_ - -namespace net { -class HttpNetworkLayer; -} - -namespace policy { - -class SystemPolicyRequestContext - : public net::URLRequestContextGetter { - public: - SystemPolicyRequestContext( - scoped_refptr<net::URLRequestContextGetter> system_context_getter, - const std::string& user_agent); - - // Overridden from net::URLRequestContextGetter: - virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE; - virtual scoped_refptr<base::SingleThreadTaskRunner> - GetNetworkTaskRunner() const OVERRIDE; - - protected: - virtual ~SystemPolicyRequestContext(); - - private: - scoped_refptr<net::URLRequestContextGetter> system_context_getter_; - - // The lazy-initialized URLRequestContext associated with this getter. - scoped_ptr<net::URLRequestContext> context_; - - // HttpNetworkLayer associated with |context_|. - scoped_ptr<net::HttpNetworkLayer> http_transaction_factory_; - - net::StaticHttpUserAgentSettings http_user_agent_settings_; - DISALLOW_COPY_AND_ASSIGN(SystemPolicyRequestContext); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_SYSTEM_POLICY_REQUEST_CONTEXT_H_ diff --git a/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc b/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc index 896f151..6092291 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc @@ -8,7 +8,7 @@ #include "base/message_loop/message_loop_proxy.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/invalidation/invalidation_service_factory.h" -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" #include "content/public/browser/notification_source.h" namespace policy { diff --git a/chrome/browser/policy/cloud/user_cloud_policy_manager.cc b/chrome/browser/policy/cloud/user_cloud_policy_manager.cc index 77e3ada..04c1edc 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_manager.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_manager.cc @@ -7,11 +7,11 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h" #include "chrome/browser/policy/cloud/user_cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" #include "components/policy/core/common/policy_pref_names.h" #include "components/policy/core/common/policy_types.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/policy/cloud/user_cloud_policy_manager.h b/chrome/browser/policy/cloud/user_cloud_policy_manager.h index 00d4b6f..7800cf9 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_manager.h +++ b/chrome/browser/policy/cloud/user_cloud_policy_manager.h @@ -12,8 +12,8 @@ #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" #include "components/browser_context_keyed_service/browser_context_keyed_service.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" class PrefService; diff --git a/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc b/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc index 0deeaca..dc5cb05 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc @@ -8,12 +8,12 @@ #include "base/logging.h" #include "base/message_loop/message_loop_proxy.h" #include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" #include "chrome/browser/policy/cloud/user_cloud_policy_store.h" #include "chrome/browser/policy/schema_registry_service.h" #include "chrome/browser/policy/schema_registry_service_factory.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "content/public/browser/browser_context.h" namespace policy { diff --git a/chrome/browser/policy/cloud/user_cloud_policy_manager_unittest.cc b/chrome/browser/policy/cloud/user_cloud_policy_manager_unittest.cc index cae8a00..524f589 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_manager_unittest.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_manager_unittest.cc @@ -8,8 +8,8 @@ #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "base/sequenced_task_runner.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" #include "chrome/browser/policy/cloud/mock_user_cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/schema_registry.h" diff --git a/chrome/browser/policy/cloud/user_cloud_policy_store_base.cc b/chrome/browser/policy/cloud/user_cloud_policy_store_base.cc index 1f36ad1..478d686 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_store_base.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_store_base.cc @@ -4,8 +4,8 @@ #include "chrome/browser/policy/cloud/user_cloud_policy_store_base.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/policy_map.h" #include "policy/proto/cloud_policy.pb.h" diff --git a/chrome/browser/policy/cloud/user_cloud_policy_store_base.h b/chrome/browser/policy/cloud/user_cloud_policy_store_base.h index 068002e..1a1f088 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_store_base.h +++ b/chrome/browser/policy/cloud/user_cloud_policy_store_base.h @@ -11,8 +11,8 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" namespace base { class SequencedTaskRunner; diff --git a/chrome/browser/policy/cloud/user_cloud_policy_store_unittest.cc b/chrome/browser/policy/cloud/user_cloud_policy_store_unittest.cc index d07e622..8554f35 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_store_unittest.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_store_unittest.cc @@ -9,9 +9,9 @@ #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "base/run_loop.h" -#include "chrome/browser/policy/cloud/mock_cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h" -#include "chrome/browser/policy/cloud/policy_builder.h" +#include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" +#include "components/policy/core/common/cloud/policy_builder.h" #include "net/url_request/url_request_context_getter.h" #include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" diff --git a/chrome/browser/policy/cloud/user_info_fetcher.cc b/chrome/browser/policy/cloud/user_info_fetcher.cc deleted file mode 100644 index 23088a5..0000000 --- a/chrome/browser/policy/cloud/user_info_fetcher.cc +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/user_info_fetcher.h" - -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/strings/stringprintf.h" -#include "base/values.h" -#include "google_apis/gaia/gaia_urls.h" -#include "google_apis/gaia/google_service_auth_error.h" -#include "net/base/load_flags.h" -#include "net/http/http_status_code.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_status.h" -#include "url/gurl.h" - -namespace { - -static const char kAuthorizationHeaderFormat[] = - "Authorization: Bearer %s"; - -static std::string MakeAuthorizationHeader(const std::string& auth_token) { - return base::StringPrintf(kAuthorizationHeaderFormat, auth_token.c_str()); -} - -} // namespace - -namespace policy { - -UserInfoFetcher::UserInfoFetcher(Delegate* delegate, - net::URLRequestContextGetter* context) - : delegate_(delegate), - context_(context) { - DCHECK(delegate); -} - -UserInfoFetcher::~UserInfoFetcher() { -} - -void UserInfoFetcher::Start(const std::string& access_token) { - // Create a URLFetcher and start it. - url_fetcher_.reset(net::URLFetcher::Create( - 0, GaiaUrls::GetInstance()->oauth_user_info_url(), - net::URLFetcher::GET, this)); - url_fetcher_->SetRequestContext(context_); - url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SAVE_COOKIES); - url_fetcher_->AddExtraRequestHeader(MakeAuthorizationHeader(access_token)); - url_fetcher_->Start(); // Results in a call to OnURLFetchComplete(). -} - -void UserInfoFetcher::OnURLFetchComplete(const net::URLFetcher* source) { - net::URLRequestStatus status = source->GetStatus(); - GoogleServiceAuthError error = GoogleServiceAuthError::AuthErrorNone(); - if (!status.is_success()) { - if (status.status() == net::URLRequestStatus::CANCELED) - error = GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED); - else - error = GoogleServiceAuthError::FromConnectionError(status.error()); - } else if (source->GetResponseCode() != net::HTTP_OK) { - DLOG(WARNING) << "UserInfo request failed with HTTP code: " - << source->GetResponseCode(); - error = GoogleServiceAuthError( - GoogleServiceAuthError::CONNECTION_FAILED); - } - if (error.state() != GoogleServiceAuthError::NONE) { - delegate_->OnGetUserInfoFailure(error); - return; - } - - // Successfully fetched userinfo from the server - parse it and hand it off - // to the delegate. - std::string unparsed_data; - source->GetResponseAsString(&unparsed_data); - DVLOG(1) << "Received UserInfo response: " << unparsed_data; - scoped_ptr<base::Value> parsed_value(base::JSONReader::Read(unparsed_data)); - base::DictionaryValue* dict; - if (parsed_value.get() && parsed_value->GetAsDictionary(&dict)) { - delegate_->OnGetUserInfoSuccess(dict); - } else { - NOTREACHED() << "Could not parse userinfo response from server"; - delegate_->OnGetUserInfoFailure(GoogleServiceAuthError( - GoogleServiceAuthError::CONNECTION_FAILED)); - } -} - -}; // namespace policy diff --git a/chrome/browser/policy/cloud/user_info_fetcher.h b/chrome/browser/policy/cloud/user_info_fetcher.h deleted file mode 100644 index 1dab0ec..0000000 --- a/chrome/browser/policy/cloud/user_info_fetcher.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_USER_INFO_FETCHER_H_ -#define CHROME_BROWSER_POLICY_CLOUD_USER_INFO_FETCHER_H_ - -#include <string> -#include "base/memory/scoped_ptr.h" -#include "net/url_request/url_fetcher_delegate.h" - -class GoogleServiceAuthError; - -namespace base { -class DictionaryValue; -} - -namespace net { -class URLFetcher; -class URLRequestContextGetter; -} - -namespace policy { - -// Class that makes a UserInfo request, parses the response, and notifies -// a provided Delegate when the request is complete. -class UserInfoFetcher : public net::URLFetcherDelegate { - public: - class Delegate { - public: - // Invoked when the UserInfo request has succeeded, passing the parsed - // response in |response|. Delegate may free the UserInfoFetcher in this - // callback. - virtual void OnGetUserInfoSuccess( - const base::DictionaryValue* response) = 0; - - // Invoked when the UserInfo request has failed, passing the associated - // error in |error|. Delegate may free the UserInfoFetcher in this - // callback. - virtual void OnGetUserInfoFailure(const GoogleServiceAuthError& error) = 0; - }; - - // Create a new UserInfoFetcher. |context| can be NULL for unit tests. - UserInfoFetcher(Delegate* delegate, net::URLRequestContextGetter* context); - virtual ~UserInfoFetcher(); - - // Starts the UserInfo request, using the passed OAuth2 |access_token|. - void Start(const std::string& access_token); - - // net::URLFetcherDelegate implementation. - virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; - - private: - Delegate* delegate_; - net::URLRequestContextGetter* context_; - scoped_ptr<net::URLFetcher> url_fetcher_; - - DISALLOW_COPY_AND_ASSIGN(UserInfoFetcher); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_USER_INFO_FETCHER_H_ diff --git a/chrome/browser/policy/cloud/user_info_fetcher_unittest.cc b/chrome/browser/policy/cloud/user_info_fetcher_unittest.cc deleted file mode 100644 index e14422d..0000000 --- a/chrome/browser/policy/cloud/user_info_fetcher_unittest.cc +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/values.h" -#include "chrome/browser/policy/cloud/user_info_fetcher.h" -#include "google_apis/gaia/google_service_auth_error.h" -#include "net/http/http_status_code.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::_; - -namespace policy { - -namespace { - -static const char kUserInfoResponse[] = - "{" - " \"email\": \"test_user@test.com\"," - " \"verified_email\": true," - " \"hd\": \"test.com\"" - "}"; - -class MockUserInfoFetcherDelegate : public UserInfoFetcher::Delegate { - public: - MockUserInfoFetcherDelegate() {} - ~MockUserInfoFetcherDelegate() {} - MOCK_METHOD1(OnGetUserInfoFailure, - void(const GoogleServiceAuthError& error)); - MOCK_METHOD1(OnGetUserInfoSuccess, void(const DictionaryValue* result)); -}; - -MATCHER_P(MatchDict, expected, "matches DictionaryValue") { - return arg->Equals(expected); -} - -class UserInfoFetcherTest : public testing::Test { - public: - UserInfoFetcherTest() {} - net::TestURLFetcherFactory url_factory_; -}; - -TEST_F(UserInfoFetcherTest, FailedFetch) { - MockUserInfoFetcherDelegate delegate; - UserInfoFetcher fetcher(&delegate, NULL); - fetcher.Start("access_token"); - - // Fake a failed fetch - should result in the failure callback being invoked. - EXPECT_CALL(delegate, OnGetUserInfoFailure(_)); - net::TestURLFetcher* url_fetcher = url_factory_.GetFetcherByID(0); - url_fetcher->set_status(net::URLRequestStatus( - net::URLRequestStatus::FAILED, -1)); - url_fetcher->delegate()->OnURLFetchComplete(url_fetcher); -} - -TEST_F(UserInfoFetcherTest, SuccessfulFetch) { - MockUserInfoFetcherDelegate delegate; - UserInfoFetcher fetcher(&delegate, NULL); - fetcher.Start("access_token"); - - // Generate what we expect our result will look like (should match - // parsed kUserInfoResponse). - scoped_ptr<DictionaryValue> dict(new DictionaryValue()); - dict->SetString("email", "test_user@test.com"); - dict->SetBoolean("verified_email", true); - dict->SetString("hd", "test.com"); - - // Fake a successful fetch - should result in the data being parsed and - // the values passed off to the success callback. - EXPECT_CALL(delegate, OnGetUserInfoSuccess(MatchDict(dict.get()))); - net::TestURLFetcher* url_fetcher = url_factory_.GetFetcherByID(0); - url_fetcher->set_response_code(net::HTTP_OK); - url_fetcher->SetResponseString(kUserInfoResponse); - url_fetcher->delegate()->OnURLFetchComplete(url_fetcher); -} -} // namespace - -} // namespace policy diff --git a/chrome/browser/policy/cloud/user_policy_request_context.cc b/chrome/browser/policy/cloud/user_policy_request_context.cc deleted file mode 100644 index e12a2c1..0000000 --- a/chrome/browser/policy/cloud/user_policy_request_context.cc +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/cloud/user_policy_request_context.h" - -#include "base/logging.h" -#include "base/single_thread_task_runner.h" -#include "net/cookies/cookie_monster.h" -#include "net/http/http_network_layer.h" -#include "net/url_request/url_request_context.h" - -namespace policy { - -UserPolicyRequestContext::UserPolicyRequestContext( - scoped_refptr<net::URLRequestContextGetter> user_context_getter, - scoped_refptr<net::URLRequestContextGetter> system_context_getter, - const std::string& user_agent) - : user_context_getter_(user_context_getter), - system_context_getter_(system_context_getter), - http_user_agent_settings_("*", user_agent) { - DCHECK(user_context_getter_); -} - -UserPolicyRequestContext::~UserPolicyRequestContext() { -} - -net::URLRequestContext* -UserPolicyRequestContext::GetURLRequestContext() { - DCHECK(GetNetworkTaskRunner()->RunsTasksOnCurrentThread()); - if (!context_.get()) { - // Create our URLRequestContext(). - context_.reset(new net::URLRequestContext()); - net::URLRequestContext* user_context = - user_context_getter_->GetURLRequestContext(); - - // Reuse pretty much everything from the user context, except we - // use the system context's proxy and resolver (see below). - context_->CopyFrom(user_context); - - // Use the system context's proxy and resolver to ensure that we can still - // fetch policy updates even if a bad proxy config is pushed via user - // policy. - // TODO(atwilson): Re-enable the following lines in a followup CL per - // reviewer request. - // net::URLRequestContext* system_context = - // system_context_getter_->GetURLRequestContext(); - // context_->set_host_resolver(system_context->host_resolver()); - // context_->set_proxy_service(system_context->proxy_service()); - - // Set our custom UserAgent. - context_->set_http_user_agent_settings(&http_user_agent_settings_); - } - return context_.get(); -} - -scoped_refptr<base::SingleThreadTaskRunner> -UserPolicyRequestContext::GetNetworkTaskRunner() const { - return user_context_getter_->GetNetworkTaskRunner(); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud/user_policy_request_context.h b/chrome/browser/policy/cloud/user_policy_request_context.h deleted file mode 100644 index 2643fd6..0000000 --- a/chrome/browser/policy/cloud/user_policy_request_context.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/scoped_ptr.h" -#include "net/url_request/static_http_user_agent_settings.h" -#include "net/url_request/url_request_context_getter.h" - -#ifndef CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_REQUEST_CONTEXT_H_ -#define CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_REQUEST_CONTEXT_H_ - -namespace net { -class HttpNetworkLayer; -} - -namespace policy { - -class UserPolicyRequestContext - : public net::URLRequestContextGetter { - public: - UserPolicyRequestContext( - scoped_refptr<net::URLRequestContextGetter> user_context_getter, - scoped_refptr<net::URLRequestContextGetter> system_context_getter, - const std::string& user_agent); - - // Overridden from net::URLRequestContextGetter: - virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE; - virtual scoped_refptr<base::SingleThreadTaskRunner> - GetNetworkTaskRunner() const OVERRIDE; - - protected: - virtual ~UserPolicyRequestContext(); - - private: - scoped_refptr<net::URLRequestContextGetter> user_context_getter_; - scoped_refptr<net::URLRequestContextGetter> system_context_getter_; - - // The lazy-initialized URLRequestContext associated with this getter. - scoped_ptr<net::URLRequestContext> context_; - - // HttpNetworkLayer associated with |context_|. - scoped_ptr<net::HttpNetworkLayer> http_transaction_factory_; - - net::StaticHttpUserAgentSettings http_user_agent_settings_; - DISALLOW_COPY_AND_ASSIGN(UserPolicyRequestContext); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_REQUEST_CONTEXT_H_ diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.cc b/chrome/browser/policy/cloud/user_policy_signin_service.cc index c9598d4b..e0031df 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service.cc @@ -9,13 +9,13 @@ #include "base/callback.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/profile_oauth2_token_service.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_client_registration_helper.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "google_apis/gaia/gaia_constants.h" diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_android.cc b/chrome/browser/policy/cloud/user_policy_signin_service_android.cc index b71ec77..6efa336 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_android.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_android.cc @@ -12,7 +12,6 @@ #include "base/message_loop/message_loop.h" #include "base/prefs/pref_service.h" #include "base/time/time.h" -#include "chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" #include "chrome/browser/profiles/profile.h" @@ -20,6 +19,7 @@ #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/common/cloud/cloud_policy_client_registration_helper.h" #include "components/policy/core/common/policy_switches.h" #include "net/base/network_change_notifier.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc index 0382bed..19fd8dd 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc @@ -9,14 +9,14 @@ #include "base/message_loop/message_loop.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/device_management_service.h" -#include "chrome/browser/policy/cloud/system_policy_request_context.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h" -#include "chrome/browser/policy/cloud/user_policy_request_context.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/common/chrome_switches.h" +#include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/system_policy_request_context.h" +#include "components/policy/core/common/cloud/user_policy_request_context.h" #include "content/public/browser/notification_source.h" #include "content/public/common/content_client.h" #include "net/url_request/url_request_context_getter.h" diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_base.h b/chrome/browser/policy/cloud/user_policy_signin_service_base.h index 91ceedc..d72aa7d 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.h @@ -13,9 +13,9 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_service.h" #include "components/browser_context_keyed_service/browser_context_keyed_service.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_service.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc index de85e3d..387a7b8 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc @@ -11,9 +11,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/mock_device_management_service.h" #include "chrome/browser/policy/cloud/mock_user_cloud_policy_store.h" #include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h" @@ -27,6 +24,9 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_pref_service_syncable.h" #include "chrome/test/base/testing_profile.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/mock_device_management_service.h" #include "components/policy/core/common/schema_registry.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/notification_details.h" diff --git a/chrome/browser/policy/config_dir_policy_loader.cc b/chrome/browser/policy/config_dir_policy_loader.cc deleted file mode 100644 index b35064d..0000000 --- a/chrome/browser/policy/config_dir_policy_loader.cc +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/config_dir_policy_loader.h" - -#include <algorithm> -#include <set> -#include <string> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/file_util.h" -#include "base/files/file_enumerator.h" -#include "base/json/json_file_value_serializer.h" -#include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/platform_file.h" -#include "base/stl_util.h" -#include "chrome/browser/policy/policy_load_status.h" -#include "components/policy/core/common/policy_bundle.h" - -namespace policy { - -namespace { - -// Subdirectories that contain the mandatory and recommended policies. -const base::FilePath::CharType kMandatoryConfigDir[] = - FILE_PATH_LITERAL("managed"); -const base::FilePath::CharType kRecommendedConfigDir[] = - FILE_PATH_LITERAL("recommended"); - -PolicyLoadStatus JsonErrorToPolicyLoadStatus(int status) { - switch (status) { - case JSONFileValueSerializer::JSON_ACCESS_DENIED: - case JSONFileValueSerializer::JSON_CANNOT_READ_FILE: - case JSONFileValueSerializer::JSON_FILE_LOCKED: - return POLICY_LOAD_STATUS_READ_ERROR; - case JSONFileValueSerializer::JSON_NO_SUCH_FILE: - return POLICY_LOAD_STATUS_MISSING; - case base::JSONReader::JSON_INVALID_ESCAPE: - case base::JSONReader::JSON_SYNTAX_ERROR: - case base::JSONReader::JSON_UNEXPECTED_TOKEN: - case base::JSONReader::JSON_TRAILING_COMMA: - case base::JSONReader::JSON_TOO_MUCH_NESTING: - case base::JSONReader::JSON_UNEXPECTED_DATA_AFTER_ROOT: - case base::JSONReader::JSON_UNSUPPORTED_ENCODING: - case base::JSONReader::JSON_UNQUOTED_DICTIONARY_KEY: - return POLICY_LOAD_STATUS_PARSE_ERROR; - case base::JSONReader::JSON_NO_ERROR: - NOTREACHED(); - return POLICY_LOAD_STATUS_STARTED; - } - NOTREACHED() << "Invalid status " << status; - return POLICY_LOAD_STATUS_PARSE_ERROR; -} - -} // namespace - -ConfigDirPolicyLoader::ConfigDirPolicyLoader( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const base::FilePath& config_dir, - PolicyScope scope) - : AsyncPolicyLoader(task_runner), config_dir_(config_dir), scope_(scope) {} - -ConfigDirPolicyLoader::~ConfigDirPolicyLoader() {} - -void ConfigDirPolicyLoader::InitOnBackgroundThread() { - base::FilePathWatcher::Callback callback = - base::Bind(&ConfigDirPolicyLoader::OnFileUpdated, base::Unretained(this)); - mandatory_watcher_.Watch(config_dir_.Append(kMandatoryConfigDir), false, - callback); - recommended_watcher_.Watch(config_dir_.Append(kRecommendedConfigDir), false, - callback); -} - -scoped_ptr<PolicyBundle> ConfigDirPolicyLoader::Load() { - scoped_ptr<PolicyBundle> bundle(new PolicyBundle()); - LoadFromPath(config_dir_.Append(kMandatoryConfigDir), - POLICY_LEVEL_MANDATORY, - bundle.get()); - LoadFromPath(config_dir_.Append(kRecommendedConfigDir), - POLICY_LEVEL_RECOMMENDED, - bundle.get()); - return bundle.Pass(); -} - -base::Time ConfigDirPolicyLoader::LastModificationTime() { - static const base::FilePath::CharType* kConfigDirSuffixes[] = { - kMandatoryConfigDir, - kRecommendedConfigDir, - }; - - base::Time last_modification = base::Time(); - base::PlatformFileInfo info; - - for (size_t i = 0; i < arraysize(kConfigDirSuffixes); ++i) { - base::FilePath path(config_dir_.Append(kConfigDirSuffixes[i])); - - // Skip if the file doesn't exist, or it isn't a directory. - if (!base::GetFileInfo(path, &info) || !info.is_directory) - continue; - - // Enumerate the files and find the most recent modification timestamp. - base::FileEnumerator file_enumerator(path, false, - base::FileEnumerator::FILES); - for (base::FilePath config_file = file_enumerator.Next(); - !config_file.empty(); - config_file = file_enumerator.Next()) { - if (base::GetFileInfo(config_file, &info) && !info.is_directory) - last_modification = std::max(last_modification, info.last_modified); - } - } - - return last_modification; -} - -void ConfigDirPolicyLoader::LoadFromPath(const base::FilePath& path, - PolicyLevel level, - PolicyBundle* bundle) { - // Enumerate the files and sort them lexicographically. - std::set<base::FilePath> files; - base::FileEnumerator file_enumerator(path, false, - base::FileEnumerator::FILES); - for (base::FilePath config_file_path = file_enumerator.Next(); - !config_file_path.empty(); config_file_path = file_enumerator.Next()) - files.insert(config_file_path); - - PolicyLoadStatusSample status; - if (files.empty()) { - status.Add(POLICY_LOAD_STATUS_NO_POLICY); - return; - } - - // Start with an empty dictionary and merge the files' contents. - // The files are processed in reverse order because |MergeFrom| gives priority - // to existing keys, but the ConfigDirPolicyProvider gives priority to the - // last file in lexicographic order. - for (std::set<base::FilePath>::reverse_iterator config_file_iter = - files.rbegin(); config_file_iter != files.rend(); - ++config_file_iter) { - JSONFileValueSerializer deserializer(*config_file_iter); - deserializer.set_allow_trailing_comma(true); - int error_code = 0; - std::string error_msg; - scoped_ptr<base::Value> value( - deserializer.Deserialize(&error_code, &error_msg)); - if (!value.get()) { - LOG(WARNING) << "Failed to read configuration file " - << config_file_iter->value() << ": " << error_msg; - status.Add(JsonErrorToPolicyLoadStatus(error_code)); - continue; - } - base::DictionaryValue* dictionary_value = NULL; - if (!value->GetAsDictionary(&dictionary_value)) { - LOG(WARNING) << "Expected JSON dictionary in configuration file " - << config_file_iter->value(); - status.Add(POLICY_LOAD_STATUS_PARSE_ERROR); - continue; - } - - // Detach the "3rdparty" node. - scoped_ptr<base::Value> third_party; - if (dictionary_value->Remove("3rdparty", &third_party)) - Merge3rdPartyPolicy(third_party.get(), level, bundle); - - // Add chrome policy. - PolicyMap policy_map; - policy_map.LoadFrom(dictionary_value, level, scope_); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .MergeFrom(policy_map); - } -} - -void ConfigDirPolicyLoader::Merge3rdPartyPolicy( - const base::Value* policies, - PolicyLevel level, - PolicyBundle* bundle) { - // The first-level entries in |policies| are PolicyDomains. The second-level - // entries are component IDs, and the third-level entries are the policies - // for that domain/component namespace. - - const base::DictionaryValue* domains_dictionary; - if (!policies->GetAsDictionary(&domains_dictionary)) { - LOG(WARNING) << "3rdparty value is not a dictionary!"; - return; - } - - // Helper to lookup a domain given its string name. - std::map<std::string, PolicyDomain> supported_domains; - supported_domains["extensions"] = POLICY_DOMAIN_EXTENSIONS; - - for (base::DictionaryValue::Iterator domains_it(*domains_dictionary); - !domains_it.IsAtEnd(); domains_it.Advance()) { - if (!ContainsKey(supported_domains, domains_it.key())) { - LOG(WARNING) << "Unsupported 3rd party policy domain: " - << domains_it.key(); - continue; - } - - const base::DictionaryValue* components_dictionary; - if (!domains_it.value().GetAsDictionary(&components_dictionary)) { - LOG(WARNING) << "3rdparty/" << domains_it.key() - << " value is not a dictionary!"; - continue; - } - - PolicyDomain domain = supported_domains[domains_it.key()]; - for (base::DictionaryValue::Iterator components_it(*components_dictionary); - !components_it.IsAtEnd(); components_it.Advance()) { - const base::DictionaryValue* policy_dictionary; - if (!components_it.value().GetAsDictionary(&policy_dictionary)) { - LOG(WARNING) << "3rdparty/" << domains_it.key() << "/" - << components_it.key() << " value is not a dictionary!"; - continue; - } - - PolicyMap policy; - policy.LoadFrom(policy_dictionary, level, scope_); - bundle->Get(PolicyNamespace(domain, components_it.key())) - .MergeFrom(policy); - } - } -} - -void ConfigDirPolicyLoader::OnFileUpdated(const base::FilePath& path, - bool error) { - if (!error) - Reload(false); -} - -} // namespace policy diff --git a/chrome/browser/policy/config_dir_policy_loader.h b/chrome/browser/policy/config_dir_policy_loader.h deleted file mode 100644 index fc7cc5c3..0000000 --- a/chrome/browser/policy/config_dir_policy_loader.h +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CONFIG_DIR_POLICY_LOADER_H_ -#define CHROME_BROWSER_POLICY_CONFIG_DIR_POLICY_LOADER_H_ - -#include "base/files/file_path.h" -#include "base/files/file_path_watcher.h" -#include "components/policy/core/common/async_policy_loader.h" -#include "components/policy/core/common/policy_types.h" - -namespace base { -class Value; -} - -namespace policy { - -// A policy loader implementation backed by a set of files in a given -// directory. The files should contain JSON-formatted policy settings. They are -// merged together and the result is returned in a PolicyBundle. -// The files are consulted in lexicographic file name order, so the -// last value read takes precedence in case of policy key collisions. -class ConfigDirPolicyLoader : public AsyncPolicyLoader { - public: - ConfigDirPolicyLoader(scoped_refptr<base::SequencedTaskRunner> task_runner, - const base::FilePath& config_dir, - PolicyScope scope); - virtual ~ConfigDirPolicyLoader(); - - // AsyncPolicyLoader implementation. - virtual void InitOnBackgroundThread() OVERRIDE; - virtual scoped_ptr<PolicyBundle> Load() OVERRIDE; - virtual base::Time LastModificationTime() OVERRIDE; - - private: - // Loads the policy files at |path| into the |bundle|, with the given |level|. - void LoadFromPath(const base::FilePath& path, - PolicyLevel level, - PolicyBundle* bundle); - - // Merges the 3rd party |policies| into the |bundle|, with the given |level|. - void Merge3rdPartyPolicy(const base::Value* policies, - PolicyLevel level, - PolicyBundle* bundle); - - // Callback for the FilePathWatchers. - void OnFileUpdated(const base::FilePath& path, bool error); - - // The directory containing the policy files. - base::FilePath config_dir_; - - // Policies loaded by this provider will have this scope. - PolicyScope scope_; - - // Watchers for events on the mandatory and recommended subdirectories of - // |config_dir_|. - base::FilePathWatcher mandatory_watcher_; - base::FilePathWatcher recommended_watcher_; - - DISALLOW_COPY_AND_ASSIGN(ConfigDirPolicyLoader); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CONFIG_DIR_POLICY_LOADER_H_ diff --git a/chrome/browser/policy/config_dir_policy_loader_unittest.cc b/chrome/browser/policy/config_dir_policy_loader_unittest.cc deleted file mode 100644 index c2838cd..0000000 --- a/chrome/browser/policy/config_dir_policy_loader_unittest.cc +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/compiler_specific.h" -#include "base/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/json/json_string_value_serializer.h" -#include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" -#include "base/message_loop/message_loop_proxy.h" -#include "base/sequenced_task_runner.h" -#include "base/strings/string_number_conversions.h" -#include "base/values.h" -#include "chrome/browser/policy/config_dir_policy_loader.h" -#include "components/policy/core/common/async_policy_provider.h" -#include "components/policy/core/common/configuration_policy_provider_test.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" - -namespace policy { - -namespace { - -// Subdirectory of the config dir that contains mandatory policies. -const base::FilePath::CharType kMandatoryPath[] = FILE_PATH_LITERAL("managed"); - -class TestHarness : public PolicyProviderTestHarness { - public: - TestHarness(); - virtual ~TestHarness(); - - virtual void SetUp() OVERRIDE; - - virtual ConfigurationPolicyProvider* CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE; - - virtual void InstallEmptyPolicy() OVERRIDE; - virtual void InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) OVERRIDE; - virtual void InstallIntegerPolicy(const std::string& policy_name, - int policy_value) OVERRIDE; - virtual void InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) OVERRIDE; - virtual void InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) OVERRIDE; - virtual void InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) OVERRIDE; - virtual void Install3rdPartyPolicy( - const base::DictionaryValue* policies) OVERRIDE; - - const base::FilePath& test_dir() { return test_dir_.path(); } - - // JSON-encode a dictionary and write it to a file. - void WriteConfigFile(const base::DictionaryValue& dict, - const std::string& file_name); - - // Returns a unique name for a policy file. Each subsequent call returns a new - // name that comes lexicographically after the previous one. - std::string NextConfigFileName(); - - static PolicyProviderTestHarness* Create(); - - private: - base::ScopedTempDir test_dir_; - int next_policy_file_index_; - - DISALLOW_COPY_AND_ASSIGN(TestHarness); -}; - -TestHarness::TestHarness() - : PolicyProviderTestHarness(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE), - next_policy_file_index_(100) {} - -TestHarness::~TestHarness() {} - -void TestHarness::SetUp() { - ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); -} - -ConfigurationPolicyProvider* TestHarness::CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) { - scoped_ptr<AsyncPolicyLoader> loader(new ConfigDirPolicyLoader( - task_runner, test_dir(), POLICY_SCOPE_MACHINE)); - return new AsyncPolicyProvider(registry, loader.Pass()); -} - -void TestHarness::InstallEmptyPolicy() { - base::DictionaryValue dict; - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) { - base::DictionaryValue dict; - dict.SetString(policy_name, policy_value); - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::InstallIntegerPolicy(const std::string& policy_name, - int policy_value) { - base::DictionaryValue dict; - dict.SetInteger(policy_name, policy_value); - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) { - base::DictionaryValue dict; - dict.SetBoolean(policy_name, policy_value); - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::InstallStringListPolicy(const std::string& policy_name, - const base::ListValue* policy_value) { - base::DictionaryValue dict; - dict.Set(policy_name, policy_value->DeepCopy()); - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) { - base::DictionaryValue dict; - dict.Set(policy_name, policy_value->DeepCopy()); - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::Install3rdPartyPolicy(const base::DictionaryValue* policies) { - base::DictionaryValue dict; - dict.Set("3rdparty", policies->DeepCopy()); - WriteConfigFile(dict, NextConfigFileName()); -} - -void TestHarness::WriteConfigFile(const base::DictionaryValue& dict, - const std::string& file_name) { - std::string data; - JSONStringValueSerializer serializer(&data); - serializer.Serialize(dict); - const base::FilePath mandatory_dir(test_dir().Append(kMandatoryPath)); - ASSERT_TRUE(base::CreateDirectory(mandatory_dir)); - const base::FilePath file_path(mandatory_dir.AppendASCII(file_name)); - ASSERT_EQ((int) data.size(), - file_util::WriteFile(file_path, data.c_str(), data.size())); -} - -std::string TestHarness::NextConfigFileName() { - EXPECT_LE(next_policy_file_index_, 999); - return std::string("policy") + base::IntToString(next_policy_file_index_++); -} - -// static -PolicyProviderTestHarness* TestHarness::Create() { - return new TestHarness(); -} - -} // namespace - -// Instantiate abstract test case for basic policy reading tests. -INSTANTIATE_TEST_CASE_P( - ConfigDirPolicyLoaderTest, - ConfigurationPolicyProviderTest, - testing::Values(TestHarness::Create)); - -// Instantiate abstract test case for 3rd party policy reading tests. -INSTANTIATE_TEST_CASE_P( - ConfigDir3rdPartyPolicyLoaderTest, - Configuration3rdPartyPolicyProviderTest, - testing::Values(TestHarness::Create)); - -// Some tests that exercise special functionality in ConfigDirPolicyLoader. -class ConfigDirPolicyLoaderTest : public PolicyTestBase { - protected: - virtual void SetUp() OVERRIDE { - PolicyTestBase::SetUp(); - harness_.SetUp(); - } - - TestHarness harness_; -}; - -// The preferences dictionary is expected to be empty when there are no files to -// load. -TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsEmpty) { - ConfigDirPolicyLoader loader( - loop_.message_loop_proxy(), harness_.test_dir(), POLICY_SCOPE_MACHINE); - scoped_ptr<PolicyBundle> bundle(loader.Load()); - ASSERT_TRUE(bundle.get()); - const PolicyBundle kEmptyBundle; - EXPECT_TRUE(bundle->Equals(kEmptyBundle)); -} - -// Reading from a non-existent directory should result in an empty preferences -// dictionary. -TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsNonExistentDirectory) { - base::FilePath non_existent_dir( - harness_.test_dir().Append(FILE_PATH_LITERAL("not_there"))); - ConfigDirPolicyLoader loader( - loop_.message_loop_proxy(), non_existent_dir, POLICY_SCOPE_MACHINE); - scoped_ptr<PolicyBundle> bundle(loader.Load()); - ASSERT_TRUE(bundle.get()); - const PolicyBundle kEmptyBundle; - EXPECT_TRUE(bundle->Equals(kEmptyBundle)); -} - -// Test merging values from different files. -TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsMergePrefs) { - // Write a bunch of data files in order to increase the chance to detect the - // provider not respecting lexicographic ordering when reading them. Since the - // filesystem may return files in arbitrary order, there is no way to be sure, - // but this is better than nothing. - base::DictionaryValue test_dict_bar; - test_dict_bar.SetString("HomepageLocation", "http://bar.com"); - for (unsigned int i = 1; i <= 4; ++i) - harness_.WriteConfigFile(test_dict_bar, base::IntToString(i)); - base::DictionaryValue test_dict_foo; - test_dict_foo.SetString("HomepageLocation", "http://foo.com"); - harness_.WriteConfigFile(test_dict_foo, "9"); - for (unsigned int i = 5; i <= 8; ++i) - harness_.WriteConfigFile(test_dict_bar, base::IntToString(i)); - - ConfigDirPolicyLoader loader( - loop_.message_loop_proxy(), harness_.test_dir(), POLICY_SCOPE_USER); - scoped_ptr<PolicyBundle> bundle(loader.Load()); - ASSERT_TRUE(bundle.get()); - PolicyBundle expected_bundle; - expected_bundle.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .LoadFrom(&test_dict_foo, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER); - EXPECT_TRUE(bundle->Equals(expected_bundle)); -} - -} // namespace policy diff --git a/chrome/browser/policy/configuration_policy_handler.cc b/chrome/browser/policy/configuration_policy_handler.cc deleted file mode 100644 index d0341d9..0000000 --- a/chrome/browser/policy/configuration_policy_handler.cc +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/configuration_policy_handler.h" - -#include <algorithm> - -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/prefs/pref_value_map.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "components/policy/core/browser/policy_error_map.h" -#include "components/policy/core/common/policy_map.h" -#include "grit/component_strings.h" -#include "url/gurl.h" - -namespace policy { - -// ConfigurationPolicyHandler implementation ----------------------------------- - -// static -std::string ConfigurationPolicyHandler::ValueTypeToString(Value::Type type) { - static const char* strings[] = { - "null", - "boolean", - "integer", - "double", - "string", - "binary", - "dictionary", - "list" - }; - CHECK(static_cast<size_t>(type) < arraysize(strings)); - return std::string(strings[type]); -} - -ConfigurationPolicyHandler::ConfigurationPolicyHandler() { -} - -ConfigurationPolicyHandler::~ConfigurationPolicyHandler() { -} - -void ConfigurationPolicyHandler::PrepareForDisplaying( - PolicyMap* policies) const {} - - -// TypeCheckingPolicyHandler implementation ------------------------------------ - -TypeCheckingPolicyHandler::TypeCheckingPolicyHandler( - const char* policy_name, - Value::Type value_type) - : policy_name_(policy_name), - value_type_(value_type) { -} - -TypeCheckingPolicyHandler::~TypeCheckingPolicyHandler() { -} - -const char* TypeCheckingPolicyHandler::policy_name() const { - return policy_name_; -} - -bool TypeCheckingPolicyHandler::CheckPolicySettings(const PolicyMap& policies, - PolicyErrorMap* errors) { - const Value* value = NULL; - return CheckAndGetValue(policies, errors, &value); -} - -bool TypeCheckingPolicyHandler::CheckAndGetValue(const PolicyMap& policies, - PolicyErrorMap* errors, - const Value** value) { - *value = policies.GetValue(policy_name_); - if (*value && !(*value)->IsType(value_type_)) { - errors->AddError(policy_name_, - IDS_POLICY_TYPE_ERROR, - ValueTypeToString(value_type_)); - return false; - } - return true; -} - - -// IntRangePolicyHandlerBase implementation ------------------------------------ - -IntRangePolicyHandlerBase::IntRangePolicyHandlerBase( - const char* policy_name, - int min, - int max, - bool clamp) - : TypeCheckingPolicyHandler(policy_name, base::Value::TYPE_INTEGER), - min_(min), - max_(max), - clamp_(clamp) { -} - -bool IntRangePolicyHandlerBase::CheckPolicySettings(const PolicyMap& policies, - PolicyErrorMap* errors) { - const base::Value* value; - return CheckAndGetValue(policies, errors, &value) && - EnsureInRange(value, NULL, errors); -} - -IntRangePolicyHandlerBase::~IntRangePolicyHandlerBase() { -} - -bool IntRangePolicyHandlerBase::EnsureInRange(const base::Value* input, - int* output, - PolicyErrorMap* errors) { - if (!input) - return true; - - int value; - if (!input->GetAsInteger(&value)) { - NOTREACHED(); - return false; - } - - if (value < min_ || value > max_) { - if (errors) { - errors->AddError(policy_name(), - IDS_POLICY_OUT_OF_RANGE_ERROR, - base::IntToString(value)); - } - - if (!clamp_) - return false; - - value = std::min(std::max(value, min_), max_); - } - - if (output) - *output = value; - return true; -} - - -// StringToIntEnumListPolicyHandler implementation ----------------------------- - -StringToIntEnumListPolicyHandler::StringToIntEnumListPolicyHandler( - const char* policy_name, - const char* pref_path, - const MappingEntry* mapping_begin, - const MappingEntry* mapping_end) - : TypeCheckingPolicyHandler(policy_name, base::Value::TYPE_LIST), - pref_path_(pref_path), - mapping_begin_(mapping_begin), - mapping_end_(mapping_end) {} - -bool StringToIntEnumListPolicyHandler::CheckPolicySettings( - const PolicyMap& policies, - PolicyErrorMap* errors) { - const base::Value* value; - return CheckAndGetValue(policies, errors, &value) && - Convert(value, NULL, errors); -} - -void StringToIntEnumListPolicyHandler::ApplyPolicySettings( - const PolicyMap& policies, - PrefValueMap* prefs) { - if (!pref_path_) - return; - const base::Value* value = policies.GetValue(policy_name()); - scoped_ptr<base::ListValue> list(new base::ListValue()); - if (value && Convert(value, list.get(), NULL)) - prefs->SetValue(pref_path_, list.release()); -} - -bool StringToIntEnumListPolicyHandler::Convert(const base::Value* input, - base::ListValue* output, - PolicyErrorMap* errors) { - if (!input) - return true; - - const base::ListValue* list_value = NULL; - if (!input->GetAsList(&list_value)) { - NOTREACHED(); - return false; - } - - for (base::ListValue::const_iterator entry(list_value->begin()); - entry != list_value->end(); ++entry) { - std::string entry_value; - if (!(*entry)->GetAsString(&entry_value)) { - if (errors) { - errors->AddError(policy_name(), - entry - list_value->begin(), - IDS_POLICY_TYPE_ERROR, - ValueTypeToString(base::Value::TYPE_STRING)); - } - continue; - } - bool found = false; - for (const MappingEntry* mapping_entry(mapping_begin_); - mapping_entry != mapping_end_; ++mapping_entry) { - if (mapping_entry->enum_value == entry_value) { - found = true; - if (output) - output->AppendInteger(mapping_entry->int_value); - break; - } - } - if (!found) { - if (errors) { - errors->AddError(policy_name(), - entry - list_value->begin(), - IDS_POLICY_OUT_OF_RANGE_ERROR); - } - } - } - - return true; -} - - -// IntRangePolicyHandler implementation ---------------------------------------- - -IntRangePolicyHandler::IntRangePolicyHandler(const char* policy_name, - const char* pref_path, - int min, - int max, - bool clamp) - : IntRangePolicyHandlerBase(policy_name, min, max, clamp), - pref_path_(pref_path) { -} - -IntRangePolicyHandler::~IntRangePolicyHandler() { -} - -void IntRangePolicyHandler::ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) { - if (!pref_path_) - return; - const base::Value* value = policies.GetValue(policy_name()); - int value_in_range; - if (value && EnsureInRange(value, &value_in_range, NULL)) { - prefs->SetValue(pref_path_, - base::Value::CreateIntegerValue(value_in_range)); - } -} - - -// IntPercentageToDoublePolicyHandler implementation --------------------------- - -IntPercentageToDoublePolicyHandler::IntPercentageToDoublePolicyHandler( - const char* policy_name, - const char* pref_path, - int min, - int max, - bool clamp) - : IntRangePolicyHandlerBase(policy_name, min, max, clamp), - pref_path_(pref_path) { -} - -IntPercentageToDoublePolicyHandler::~IntPercentageToDoublePolicyHandler() { -} - -void IntPercentageToDoublePolicyHandler::ApplyPolicySettings( - const PolicyMap& policies, - PrefValueMap* prefs) { - if (!pref_path_) - return; - const base::Value* value = policies.GetValue(policy_name()); - int percentage; - if (value && EnsureInRange(value, &percentage, NULL)) { - prefs->SetValue(pref_path_, base::Value::CreateDoubleValue( - static_cast<double>(percentage) / 100.)); - } -} - - -// SimplePolicyHandler implementation ------------------------------------------ - -SimplePolicyHandler::SimplePolicyHandler( - const char* policy_name, - const char* pref_path, - Value::Type value_type) - : TypeCheckingPolicyHandler(policy_name, value_type), - pref_path_(pref_path) { -} - -SimplePolicyHandler::~SimplePolicyHandler() { -} - -void SimplePolicyHandler::ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) { - if (!pref_path_) - return; - const Value* value = policies.GetValue(policy_name()); - if (value) - prefs->SetValue(pref_path_, value->DeepCopy()); -} - -} // namespace policy diff --git a/chrome/browser/policy/configuration_policy_handler.h b/chrome/browser/policy/configuration_policy_handler.h deleted file mode 100644 index f7b7eae..0000000 --- a/chrome/browser/policy/configuration_policy_handler.h +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_H_ -#define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/values.h" - -class PrefValueMap; - -namespace policy { - -class PolicyErrorMap; -class PolicyMap; - -// Maps a policy type to a preference path, and to the expected value type. -struct PolicyToPreferenceMapEntry { - const char* const policy_name; - const char* const preference_path; - const base::Value::Type value_type; -}; - -// An abstract super class that subclasses should implement to map policies to -// their corresponding preferences, and to check whether the policies are valid. -class ConfigurationPolicyHandler { - public: - static std::string ValueTypeToString(Value::Type type); - - ConfigurationPolicyHandler(); - virtual ~ConfigurationPolicyHandler(); - - // Returns whether the policy settings handled by this - // ConfigurationPolicyHandler can be applied. Fills |errors| with error - // messages or warnings. |errors| may contain error messages even when - // |CheckPolicySettings()| returns true. - virtual bool CheckPolicySettings(const PolicyMap& policies, - PolicyErrorMap* errors) = 0; - - // Processes the policies handled by this ConfigurationPolicyHandler and sets - // the appropriate preferences in |prefs|. - virtual void ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) = 0; - - // Modifies the values of some of the policies in |policies| so that they - // are more suitable to display to the user. This can be used to remove - // sensitive values such as passwords, or to pretty-print values. - virtual void PrepareForDisplaying(PolicyMap* policies) const; - - private: - DISALLOW_COPY_AND_ASSIGN(ConfigurationPolicyHandler); -}; - -// Abstract class derived from ConfigurationPolicyHandler that should be -// subclassed to handle a single policy (not a combination of policies). -class TypeCheckingPolicyHandler : public ConfigurationPolicyHandler { - public: - TypeCheckingPolicyHandler(const char* policy_name, - base::Value::Type value_type); - virtual ~TypeCheckingPolicyHandler(); - - // ConfigurationPolicyHandler methods: - virtual bool CheckPolicySettings(const PolicyMap& policies, - PolicyErrorMap* errors) OVERRIDE; - - const char* policy_name() const; - - protected: - // Runs policy checks and returns the policy value if successful. - bool CheckAndGetValue(const PolicyMap& policies, - PolicyErrorMap* errors, - const Value** value); - - private: - // The name of the policy. - const char* policy_name_; - - // The type the value of the policy should have. - base::Value::Type value_type_; - - DISALLOW_COPY_AND_ASSIGN(TypeCheckingPolicyHandler); -}; - -// Abstract class derived from TypeCheckingPolicyHandler that ensures an int -// policy's value lies in an allowed range. Either clamps or rejects values -// outside the range. -class IntRangePolicyHandlerBase : public TypeCheckingPolicyHandler { - public: - IntRangePolicyHandlerBase(const char* policy_name, - int min, - int max, - bool clamp); - - // ConfigurationPolicyHandler: - virtual bool CheckPolicySettings(const PolicyMap& policies, - PolicyErrorMap* errors) OVERRIDE; - - protected: - virtual ~IntRangePolicyHandlerBase(); - - // Ensures that the value is in the allowed range. Returns false if the value - // cannot be parsed or lies outside the allowed range and clamping is - // disabled. - bool EnsureInRange(const base::Value* input, - int* output, - PolicyErrorMap* errors); - - private: - // The minimum value allowed. - int min_; - - // The maximum value allowed. - int max_; - - // Whether to clamp values lying outside the allowed range instead of - // rejecting them. - bool clamp_; - - DISALLOW_COPY_AND_ASSIGN(IntRangePolicyHandlerBase); -}; - -// ConfigurationPolicyHandler for policies that map directly to a preference. -class SimplePolicyHandler : public TypeCheckingPolicyHandler { - public: - SimplePolicyHandler(const char* policy_name, - const char* pref_path, - base::Value::Type value_type); - virtual ~SimplePolicyHandler(); - - // ConfigurationPolicyHandler methods: - virtual void ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) OVERRIDE; - - private: - // The DictionaryValue path of the preference the policy maps to. - const char* pref_path_; - - DISALLOW_COPY_AND_ASSIGN(SimplePolicyHandler); -}; - -// A policy handler implementation that maps a string enum list to an int enum -// list as specified by a mapping table. -class StringToIntEnumListPolicyHandler : public TypeCheckingPolicyHandler { - public: - struct MappingEntry { - const char* enum_value; - int int_value; - }; - - StringToIntEnumListPolicyHandler(const char* policy_name, - const char* pref_path, - const MappingEntry* mapping_begin, - const MappingEntry* mapping_end); - - // ConfigurationPolicyHandler methods: - virtual bool CheckPolicySettings(const PolicyMap& policies, - PolicyErrorMap* errors) OVERRIDE; - virtual void ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) OVERRIDE; - - private: - // Attempts to convert the list in |input| to |output| according to the table, - // returns false on errors. - bool Convert(const base::Value* input, - base::ListValue* output, - PolicyErrorMap* errors); - - // Name of the pref to write. - const char* pref_path_; - - // The mapping table. - const MappingEntry* mapping_begin_; - const MappingEntry* mapping_end_; - - DISALLOW_COPY_AND_ASSIGN(StringToIntEnumListPolicyHandler); -}; - -// A policy handler implementation that ensures an int policy's value lies in an -// allowed range. -class IntRangePolicyHandler : public IntRangePolicyHandlerBase { - public: - IntRangePolicyHandler(const char* policy_name, - const char* pref_path, - int min, - int max, - bool clamp); - virtual ~IntRangePolicyHandler(); - - // ConfigurationPolicyHandler: - virtual void ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) OVERRIDE; - - private: - // Name of the pref to write. - const char* pref_path_; - - DISALLOW_COPY_AND_ASSIGN(IntRangePolicyHandler); -}; - -// A policy handler implementation that maps an int percentage value to a -// double. -class IntPercentageToDoublePolicyHandler : public IntRangePolicyHandlerBase { - public: - IntPercentageToDoublePolicyHandler(const char* policy_name, - const char* pref_path, - int min, - int max, - bool clamp); - virtual ~IntPercentageToDoublePolicyHandler(); - - // ConfigurationPolicyHandler: - virtual void ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs) OVERRIDE; - - private: - // Name of the pref to write. - const char* pref_path_; - - DISALLOW_COPY_AND_ASSIGN(IntPercentageToDoublePolicyHandler); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_H_ diff --git a/chrome/browser/policy/configuration_policy_handler_android.h b/chrome/browser/policy/configuration_policy_handler_android.h index b0328d9..4dc08f0 100644 --- a/chrome/browser/policy/configuration_policy_handler_android.h +++ b/chrome/browser/policy/configuration_policy_handler_android.h @@ -7,7 +7,7 @@ #include <string> -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace base { class Value; diff --git a/chrome/browser/policy/configuration_policy_handler_list.cc b/chrome/browser/policy/configuration_policy_handler_list.cc deleted file mode 100644 index 25413a7..0000000 --- a/chrome/browser/policy/configuration_policy_handler_list.cc +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/configuration_policy_handler_list.h" - -#include "base/prefs/pref_value_map.h" -#include "base/stl_util.h" -#include "chrome/browser/policy/configuration_policy_handler.h" -#include "components/policy/core/browser/policy_error_map.h" -#include "components/policy/core/common/policy_map.h" -#include "grit/component_strings.h" - -namespace policy { -ConfigurationPolicyHandlerList::ConfigurationPolicyHandlerList( - const GetChromePolicyDetailsCallback& details_callback) - : details_callback_(details_callback) {} - -ConfigurationPolicyHandlerList::~ConfigurationPolicyHandlerList() { - STLDeleteElements(&handlers_); -} - -void ConfigurationPolicyHandlerList::AddHandler( - scoped_ptr<ConfigurationPolicyHandler> handler) { - handlers_.push_back(handler.release()); -} - -void ConfigurationPolicyHandlerList::ApplyPolicySettings( - const PolicyMap& policies, - PrefValueMap* prefs, - PolicyErrorMap* errors) const { - PolicyErrorMap scoped_errors; - if (!errors) - errors = &scoped_errors; - - std::vector<ConfigurationPolicyHandler*>::const_iterator handler; - for (handler = handlers_.begin(); handler != handlers_.end(); ++handler) { - if ((*handler)->CheckPolicySettings(policies, errors) && prefs) - (*handler)->ApplyPolicySettings(policies, prefs); - } - - for (PolicyMap::const_iterator it = policies.begin(); - it != policies.end(); - ++it) { - const PolicyDetails* details = - details_callback_.is_null() ? NULL : details_callback_.Run(it->first); - if (details && details->is_deprecated) - errors->AddError(it->first, IDS_POLICY_DEPRECATED); - } -} - -void ConfigurationPolicyHandlerList::PrepareForDisplaying( - PolicyMap* policies) const { - std::vector<ConfigurationPolicyHandler*>::const_iterator handler; - for (handler = handlers_.begin(); handler != handlers_.end(); ++handler) - (*handler)->PrepareForDisplaying(policies); -} - -} // namespace policy diff --git a/chrome/browser/policy/configuration_policy_handler_list.h b/chrome/browser/policy/configuration_policy_handler_list.h deleted file mode 100644 index 95b2008..0000000 --- a/chrome/browser/policy/configuration_policy_handler_list.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_LIST_H_ -#define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_LIST_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "components/policy/core/common/policy_details.h" - -class PrefValueMap; - -namespace policy { - -class ConfigurationPolicyHandler; -class PolicyErrorMap; -class PolicyMap; -struct PolicyToPreferenceMapEntry; - -// Converts policies to their corresponding preferences by applying a list of -// ConfigurationPolicyHandler objects. This includes error checking and -// cleaning up policy values for displaying. -class ConfigurationPolicyHandlerList { - public: - explicit ConfigurationPolicyHandlerList( - const GetChromePolicyDetailsCallback& details_callback); - ~ConfigurationPolicyHandlerList(); - - // Adds a policy handler to the list. - void AddHandler(scoped_ptr<ConfigurationPolicyHandler> handler); - - // Translates |policies| to their corresponding preferences in |prefs|. - // Any errors found while processing the policies are stored in |errors|. - // |prefs| or |errors| can be NULL, and won't be filled in that case. - void ApplyPolicySettings(const PolicyMap& policies, - PrefValueMap* prefs, - PolicyErrorMap* errors) const; - - // Converts sensitive policy values to others more appropriate for displaying. - void PrepareForDisplaying(PolicyMap* policies) const; - - private: - std::vector<ConfigurationPolicyHandler*> handlers_; - GetChromePolicyDetailsCallback details_callback_; - - DISALLOW_COPY_AND_ASSIGN(ConfigurationPolicyHandlerList); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_LIST_H_ diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 4b83931..be2a138 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc @@ -11,8 +11,6 @@ #include "chrome/browser/net/disk_cache_dir_policy_handler.h" #include "chrome/browser/net/proxy_policy_handler.h" #include "chrome/browser/policy/autofill_policy_handler.h" -#include "chrome/browser/policy/configuration_policy_handler.h" -#include "chrome/browser/policy/configuration_policy_handler_list.h" #include "chrome/browser/policy/file_selection_dialogs_policy_handler.h" #include "chrome/browser/policy/javascript_policy_handler.h" #include "chrome/browser/policy/url_blacklist_policy_handler.h" @@ -21,6 +19,8 @@ #include "chrome/browser/sessions/restore_on_startup_policy_handler.h" #include "chrome/browser/sync/sync_policy_handler.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler_list.h" #include "components/policy/core/common/policy_details.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_pref_names.h" diff --git a/chrome/browser/policy/configuration_policy_handler_unittest.cc b/chrome/browser/policy/configuration_policy_handler_unittest.cc index d648f12..42277f3 100644 --- a/chrome/browser/policy/configuration_policy_handler_unittest.cc +++ b/chrome/browser/policy/configuration_policy_handler_unittest.cc @@ -5,11 +5,16 @@ #include "base/callback.h" #include "base/memory/scoped_ptr.h" #include "base/prefs/pref_value_map.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" #include "testing/gtest/include/gtest/gtest.h" +// Note: this file should move to components/policy/core/browser, but the +// components_unittests runner does not load the ResourceBundle as +// ChromeTestSuite::Initialize does, which leads to failures using +// PolicyErrorMap. + namespace policy { namespace { diff --git a/chrome/browser/policy/configuration_policy_pref_store.cc b/chrome/browser/policy/configuration_policy_pref_store.cc deleted file mode 100644 index 9c5e221..0000000 --- a/chrome/browser/policy/configuration_policy_pref_store.cc +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/configuration_policy_pref_store.h" - -#include <string> -#include <vector> - -#include "base/bind.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/prefs/pref_value_map.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/policy/configuration_policy_handler_list.h" -#include "components/policy/core/browser/policy_error_map.h" - -namespace policy { - -namespace { - -// Policies are loaded early on startup, before PolicyErrorMaps are ready to -// be retrieved. This function is posted to UI to log any errors found on -// Refresh below. -void LogErrors(PolicyErrorMap* errors) { - PolicyErrorMap::const_iterator iter; - for (iter = errors->begin(); iter != errors->end(); ++iter) { - string16 policy = ASCIIToUTF16(iter->first); - DLOG(WARNING) << "Policy " << policy << ": " << iter->second; - } -} - -} // namespace - -ConfigurationPolicyPrefStore::ConfigurationPolicyPrefStore( - PolicyService* service, - const ConfigurationPolicyHandlerList* handler_list, - PolicyLevel level) - : policy_service_(service), - handler_list_(handler_list), - level_(level) { - // Read initial policy. - prefs_.reset(CreatePreferencesFromPolicies()); - policy_service_->AddObserver(POLICY_DOMAIN_CHROME, this); -} - -void ConfigurationPolicyPrefStore::AddObserver(PrefStore::Observer* observer) { - observers_.AddObserver(observer); -} - -void ConfigurationPolicyPrefStore::RemoveObserver( - PrefStore::Observer* observer) { - observers_.RemoveObserver(observer); -} - -bool ConfigurationPolicyPrefStore::HasObservers() const { - return observers_.might_have_observers(); -} - -bool ConfigurationPolicyPrefStore::IsInitializationComplete() const { - return policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME); -} - -bool ConfigurationPolicyPrefStore::GetValue(const std::string& key, - const Value** value) const { - const Value* stored_value = NULL; - if (!prefs_.get() || !prefs_->GetValue(key, &stored_value)) - return false; - - if (value) - *value = stored_value; - return true; -} - -void ConfigurationPolicyPrefStore::OnPolicyUpdated( - const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current) { - DCHECK_EQ(POLICY_DOMAIN_CHROME, ns.domain); - DCHECK(ns.component_id.empty()); - Refresh(); -} - -void ConfigurationPolicyPrefStore::OnPolicyServiceInitialized( - PolicyDomain domain) { - if (domain == POLICY_DOMAIN_CHROME) { - FOR_EACH_OBSERVER(PrefStore::Observer, observers_, - OnInitializationCompleted(true)); - } -} - -ConfigurationPolicyPrefStore::~ConfigurationPolicyPrefStore() { - policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, this); -} - -void ConfigurationPolicyPrefStore::Refresh() { - scoped_ptr<PrefValueMap> new_prefs(CreatePreferencesFromPolicies()); - std::vector<std::string> changed_prefs; - new_prefs->GetDifferingKeys(prefs_.get(), &changed_prefs); - prefs_.swap(new_prefs); - - // Send out change notifications. - for (std::vector<std::string>::const_iterator pref(changed_prefs.begin()); - pref != changed_prefs.end(); - ++pref) { - FOR_EACH_OBSERVER(PrefStore::Observer, observers_, - OnPrefValueChanged(*pref)); - } -} - -PrefValueMap* ConfigurationPolicyPrefStore::CreatePreferencesFromPolicies() { - scoped_ptr<PrefValueMap> prefs(new PrefValueMap); - PolicyMap filtered_policies; - filtered_policies.CopyFrom(policy_service_->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))); - filtered_policies.FilterLevel(level_); - - scoped_ptr<PolicyErrorMap> errors(new PolicyErrorMap); - - handler_list_->ApplyPolicySettings(filtered_policies, - prefs.get(), - errors.get()); - - // Retrieve and log the errors once the UI loop is ready. This is only an - // issue during startup. - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&LogErrors, base::Owned(errors.release()))); - - return prefs.release(); -} - -} // namespace policy diff --git a/chrome/browser/policy/configuration_policy_pref_store.h b/chrome/browser/policy/configuration_policy_pref_store.h deleted file mode 100644 index 73261cb..0000000 --- a/chrome/browser/policy/configuration_policy_pref_store.h +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_H_ -#define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/prefs/pref_store.h" -#include "base/values.h" -#include "chrome/browser/policy/policy_service.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_types.h" - -class PrefValueMap; - -namespace policy { - -class ConfigurationPolicyHandlerList; - -// An implementation of PrefStore that bridges policy settings as read from the -// PolicyService to preferences. Converts POLICY_DOMAIN_CHROME policies a given -// PolicyLevel to their corresponding preferences. -class ConfigurationPolicyPrefStore - : public PrefStore, - public PolicyService::Observer { - public: - // Does not take ownership of |service| nor |handler_list|, which must outlive - // the store. Only policies of the given |level| will be mapped. - ConfigurationPolicyPrefStore( - PolicyService* service, - const ConfigurationPolicyHandlerList* handler_list, - PolicyLevel level); - - // PrefStore methods: - virtual void AddObserver(PrefStore::Observer* observer) OVERRIDE; - virtual void RemoveObserver(PrefStore::Observer* observer) OVERRIDE; - virtual bool HasObservers() const OVERRIDE; - virtual bool IsInitializationComplete() const OVERRIDE; - virtual bool GetValue(const std::string& key, - const Value** result) const OVERRIDE; - - // PolicyService::Observer methods: - virtual void OnPolicyUpdated(const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current) OVERRIDE; - virtual void OnPolicyServiceInitialized(PolicyDomain domain) OVERRIDE; - - private: - virtual ~ConfigurationPolicyPrefStore(); - - // Refreshes policy information, rereading policy from the policy service and - // sending out change notifications as appropriate. - void Refresh(); - - // Returns a new PrefValueMap containing the preference values that correspond - // to the policies currently provided by the policy service. - PrefValueMap* CreatePreferencesFromPolicies(); - - // The PolicyService from which policy settings are read. - PolicyService* policy_service_; - - // The policy handlers used to convert policies into their corresponding - // preferences. - const ConfigurationPolicyHandlerList* handler_list_; - - // The policy level that this PrefStore uses. - PolicyLevel level_; - - // Current policy preferences. - scoped_ptr<PrefValueMap> prefs_; - - ObserverList<PrefStore::Observer, true> observers_; - - DISALLOW_COPY_AND_ASSIGN(ConfigurationPolicyPrefStore); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_H_ diff --git a/chrome/browser/policy/configuration_policy_pref_store_test.cc b/chrome/browser/policy/configuration_policy_pref_store_test.cc new file mode 100644 index 0000000..5a0ca23 --- /dev/null +++ b/chrome/browser/policy/configuration_policy_pref_store_test.cc @@ -0,0 +1,46 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" + +#include <string> + +#include "base/run_loop.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" +#include "components/policy/core/common/policy_details.h" +#include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service_impl.h" +#include "testing/gmock/include/gmock/gmock.h" + +using testing::Return; +using testing::_; + +namespace policy { + +ConfigurationPolicyPrefStoreTest::ConfigurationPolicyPrefStoreTest() + : handler_list_(GetChromePolicyDetailsCallback()) { + EXPECT_CALL(provider_, IsInitializationComplete(_)) + .WillRepeatedly(Return(false)); + provider_.Init(); + providers_.push_back(&provider_); + policy_service_.reset(new PolicyServiceImpl( + providers_, PolicyServiceImpl::PreprocessCallback())); + store_ = new ConfigurationPolicyPrefStore( + policy_service_.get(), &handler_list_, POLICY_LEVEL_MANDATORY); +} + +ConfigurationPolicyPrefStoreTest::~ConfigurationPolicyPrefStoreTest() {} + +void ConfigurationPolicyPrefStoreTest::TearDown() { + provider_.Shutdown(); +} + +void ConfigurationPolicyPrefStoreTest::UpdateProviderPolicy( + const PolicyMap& policy) { + provider_.UpdateChromePolicy(policy); + base::RunLoop loop; + loop.RunUntilIdle(); +} + +} // namespace policy diff --git a/chrome/browser/policy/configuration_policy_pref_store_unittest.h b/chrome/browser/policy/configuration_policy_pref_store_test.h index 9d2ac72..ef8c764 100644 --- a/chrome/browser/policy/configuration_policy_pref_store_unittest.h +++ b/chrome/browser/policy/configuration_policy_pref_store_test.h @@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_UNITTEST_H_ -#define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_UNITTEST_H_ +#ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_TEST_H_ +#define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_TEST_H_ +#include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" -#include "chrome/browser/policy/configuration_policy_handler_list.h" -#include "chrome/browser/policy/policy_service_impl.h" +#include "components/policy/core/browser/configuration_policy_handler_list.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" +#include "components/policy/core/common/policy_service_impl.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { @@ -39,4 +40,4 @@ class ConfigurationPolicyPrefStoreTest : public testing::Test { } // namespace policy -#endif // CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_UNITTEST_H_ +#endif // CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PREF_STORE_TEST_H_ diff --git a/chrome/browser/policy/configuration_policy_pref_store_unittest.cc b/chrome/browser/policy/configuration_policy_pref_store_unittest.cc index 645514e..9a45c6f 100644 --- a/chrome/browser/policy/configuration_policy_pref_store_unittest.cc +++ b/chrome/browser/policy/configuration_policy_pref_store_unittest.cc @@ -2,74 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/configuration_policy_pref_store_unittest.h" - #include <string> #include "base/callback.h" #include "base/files/file_path.h" #include "base/prefs/pref_store_observer_mock.h" #include "base/run_loop.h" -#include "chrome/browser/policy/configuration_policy_handler.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/policy_service_impl.h" +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" +#include "components/policy/core/browser/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_details.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_pref_names.h" +#include "components/policy/core/common/policy_service_impl.h" #include "testing/gmock/include/gmock/gmock.h" +// Note: this file should move to components/policy/core/browser, but the +// components_unittests runner does not load the ResourceBundle as +// ChromeTestSuite::Initialize does, which leads to failures using +// PolicyErrorMap. + using testing::Mock; using testing::Return; using testing::_; namespace { + const char kTestPolicy[] = "test.policy"; const char kTestPref[] = "test.pref"; + } // namespace namespace policy { -// Holds a set of test parameters, consisting of pref name and policy name. -class PolicyAndPref { - public: - PolicyAndPref(const char* policy_name, const char* pref_name) - : policy_name_(policy_name), - pref_name_(pref_name) {} - - const char* policy_name() const { return policy_name_; } - const char* pref_name() const { return pref_name_; } - - private: - const char* policy_name_; - const char* pref_name_; -}; - -ConfigurationPolicyPrefStoreTest::ConfigurationPolicyPrefStoreTest() - : handler_list_(GetChromePolicyDetailsCallback()) { - EXPECT_CALL(provider_, IsInitializationComplete(_)) - .WillRepeatedly(Return(false)); - provider_.Init(); - providers_.push_back(&provider_); - policy_service_.reset(new PolicyServiceImpl( - providers_, PolicyServiceImpl::PreprocessCallback())); - store_ = new ConfigurationPolicyPrefStore( - policy_service_.get(), &handler_list_, POLICY_LEVEL_MANDATORY); -} - -ConfigurationPolicyPrefStoreTest::~ConfigurationPolicyPrefStoreTest() {} - -void ConfigurationPolicyPrefStoreTest::TearDown() { - provider_.Shutdown(); -} - -void ConfigurationPolicyPrefStoreTest::UpdateProviderPolicy( - const PolicyMap& policy) { - provider_.UpdateChromePolicy(policy); - base::RunLoop loop; - loop.RunUntilIdle(); -} - // Test cases for list-valued policy settings. class ConfigurationPolicyPrefStoreListTest : public ConfigurationPolicyPrefStoreTest { diff --git a/chrome/browser/policy/file_selection_dialogs_policy_handler.h b/chrome/browser/policy/file_selection_dialogs_policy_handler.h index 6208fe7..9fad2ad 100644 --- a/chrome/browser/policy/file_selection_dialogs_policy_handler.h +++ b/chrome/browser/policy/file_selection_dialogs_policy_handler.h @@ -7,7 +7,7 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { diff --git a/chrome/browser/policy/javascript_policy_handler.h b/chrome/browser/policy/javascript_policy_handler.h index a1b4b3d..68b2f4b 100644 --- a/chrome/browser/policy/javascript_policy_handler.h +++ b/chrome/browser/policy/javascript_policy_handler.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_POLICY_JAVASCRIPT_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_JAVASCRIPT_POLICY_HANDLER_H_ -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/policy/javascript_policy_handler_unittest.cc b/chrome/browser/policy/javascript_policy_handler_unittest.cc index c5b42f5..1af39c6 100644 --- a/chrome/browser/policy/javascript_policy_handler_unittest.cc +++ b/chrome/browser/policy/javascript_policy_handler_unittest.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/configuration_policy_pref_store_unittest.h" +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" #include "chrome/browser/policy/javascript_policy_handler.h" #include "chrome/common/content_settings.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/policy/mock_policy_service.cc b/chrome/browser/policy/mock_policy_service.cc deleted file mode 100644 index bc56c65..0000000 --- a/chrome/browser/policy/mock_policy_service.cc +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/mock_policy_service.h" - -namespace policy { - -MockPolicyServiceObserver::MockPolicyServiceObserver() { -} - -MockPolicyServiceObserver::~MockPolicyServiceObserver() { -} - -MockPolicyService::MockPolicyService() { -} - -MockPolicyService::~MockPolicyService() { -} - -} // namespace policy diff --git a/chrome/browser/policy/mock_policy_service.h b/chrome/browser/policy/mock_policy_service.h deleted file mode 100644 index 3c609d4..0000000 --- a/chrome/browser/policy/mock_policy_service.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_MOCK_POLICY_SERVICE_H_ -#define CHROME_BROWSER_POLICY_MOCK_POLICY_SERVICE_H_ - -#include "chrome/browser/policy/policy_service.h" -#include "testing/gmock/include/gmock/gmock.h" - -namespace policy { - -class MockPolicyServiceObserver : public PolicyService::Observer { - public: - MockPolicyServiceObserver(); - virtual ~MockPolicyServiceObserver(); - - MOCK_METHOD3(OnPolicyUpdated, void(const PolicyNamespace&, - const PolicyMap& previous, - const PolicyMap& current)); - MOCK_METHOD1(OnPolicyServiceInitialized, void(PolicyDomain)); -}; - -class MockPolicyService : public PolicyService { - public: - MockPolicyService(); - virtual ~MockPolicyService(); - - MOCK_METHOD2(AddObserver, void(PolicyDomain, Observer*)); - MOCK_METHOD2(RemoveObserver, void(PolicyDomain, Observer*)); - - MOCK_CONST_METHOD1(GetPolicies, const PolicyMap&(const PolicyNamespace&)); - MOCK_CONST_METHOD1(IsInitializationComplete, bool(PolicyDomain domain)); - MOCK_METHOD1(RefreshPolicies, void(const base::Closure&)); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_MOCK_POLICY_SERVICE_H_ diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index f5453db..2d8c175 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc @@ -48,8 +48,6 @@ #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/browser/policy/browser_policy_connector.h" #include "chrome/browser/policy/cloud/test_request_interceptor.h" -#include "chrome/browser/policy/policy_service.h" -#include "chrome/browser/policy/policy_service_impl.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/prefs/session_startup_pref.h" @@ -87,6 +85,8 @@ #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service.h" +#include "components/policy/core/common/policy_service_impl.h" #include "content/public/browser/browser_child_process_host_iterator.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" diff --git a/chrome/browser/policy/policy_load_status.cc b/chrome/browser/policy/policy_load_status.cc deleted file mode 100644 index eb632fa..0000000 --- a/chrome/browser/policy/policy_load_status.cc +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_load_status.h" - -#include "base/metrics/histogram.h" -#include "base/strings/stringprintf.h" -#include "components/policy/core/common/policy_types.h" - -namespace policy { - -namespace { - -const char kHistogramName[] = "Enterprise.PolicyLoadStatus"; - -} // namespace - -PolicyLoadStatusSample::PolicyLoadStatusSample() - : histogram_(base::LinearHistogram::FactoryGet( - kHistogramName, 1, POLICY_LOAD_STATUS_SIZE, - POLICY_LOAD_STATUS_SIZE + 1, - base::Histogram::kUmaTargetedHistogramFlag)) { - Add(POLICY_LOAD_STATUS_STARTED); -} - -PolicyLoadStatusSample::~PolicyLoadStatusSample() { - for (int i = 0; i < POLICY_LOAD_STATUS_SIZE; ++i) { - if (status_bits_[i]) - histogram_->Add(i); - } -} - -void PolicyLoadStatusSample::Add(PolicyLoadStatus status) { - status_bits_[status] = true; -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_load_status.h b/chrome/browser/policy/policy_load_status.h deleted file mode 100644 index 4f29de5..0000000 --- a/chrome/browser/policy/policy_load_status.h +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_LOAD_STATUS_H_ -#define CHROME_BROWSER_POLICY_POLICY_LOAD_STATUS_H_ - -#include <bitset> - -#include "base/basictypes.h" - -namespace base { -class HistogramBase; -} - -namespace policy { - -// UMA histogram enum for policy load status. Don't change existing constants, -// append additional constants to the end if needed. -enum PolicyLoadStatus { - // Policy load attempt started. This gets logged for each policy load attempt - // to get a baseline on the number of requests, and an arbitrary number of - // the below status codes may get added in addition. - POLICY_LOAD_STATUS_STARTED, - // System failed to determine whether there's policy. - POLICY_LOAD_STATUS_QUERY_FAILED, - // No policy present. - POLICY_LOAD_STATUS_NO_POLICY, - // Data inaccessible, such as non-local policy file. - POLICY_LOAD_STATUS_INACCCESSIBLE, - // Data missing, such as policy file not present. - POLICY_LOAD_STATUS_MISSING, - // Trying with Wow64 redirection disabled. - POLICY_LOAD_STATUS_WOW64_REDIRECTION_DISABLED, - // Data read error, for example file reading errors. - POLICY_LOAD_STATUS_READ_ERROR, - // Data too large to process. - POLICY_LOAD_STATUS_TOO_BIG, - // Parse error. - POLICY_LOAD_STATUS_PARSE_ERROR, - - // This must stay last. - POLICY_LOAD_STATUS_SIZE -}; - -// A helper for generating policy load status UMA statistics that'll collect -// histogram samples for a policy load operation and records histogram samples -// for the status codes that were seen on destruction. -class PolicyLoadStatusSample { - public: - PolicyLoadStatusSample(); - ~PolicyLoadStatusSample(); - - // Adds a status code. - void Add(PolicyLoadStatus status); - - private: - std::bitset<POLICY_LOAD_STATUS_SIZE> status_bits_; - base::HistogramBase* histogram_; - - DISALLOW_COPY_AND_ASSIGN(PolicyLoadStatusSample); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_LOAD_STATUS_H_ diff --git a/chrome/browser/policy/policy_loader_mac.cc b/chrome/browser/policy/policy_loader_mac.cc deleted file mode 100644 index 1ee42ee..0000000 --- a/chrome/browser/policy/policy_loader_mac.cc +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_loader_mac.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/file_util.h" -#include "base/mac/foundation_util.h" -#include "base/mac/scoped_cftyperef.h" -#include "base/path_service.h" -#include "base/platform_file.h" -#include "base/sequenced_task_runner.h" -#include "base/strings/sys_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/policy/policy_load_status.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/preferences_mac.h" -#include "components/policy/core/common/schema.h" -#include "components/policy/core/common/schema_map.h" - -using base::mac::CFCast; -using base::ScopedCFTypeRef; - -namespace policy { - -namespace { - -// Callback function for CFDictionaryApplyFunction. |key| and |value| are an -// entry of the CFDictionary that should be converted into an equivalent entry -// in the DictionaryValue in |context|. -void DictionaryEntryToValue(const void* key, const void* value, void* context) { - if (CFStringRef cf_key = CFCast<CFStringRef>(key)) { - base::Value* converted = - PolicyLoaderMac::CreateValueFromProperty( - static_cast<CFPropertyListRef>(value)); - if (converted) { - const std::string string = base::SysCFStringRefToUTF8(cf_key); - static_cast<base::DictionaryValue *>(context)->Set(string, converted); - } - } -} - -// Callback function for CFArrayApplyFunction. |value| is an entry of the -// CFArray that should be converted into an equivalent entry in the ListValue -// in |context|. -void ArrayEntryToValue(const void* value, void* context) { - base::Value* converted = - PolicyLoaderMac::CreateValueFromProperty( - static_cast<CFPropertyListRef>(value)); - if (converted) - static_cast<base::ListValue *>(context)->Append(converted); -} - -} // namespace - -PolicyLoaderMac::PolicyLoaderMac( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const base::FilePath& managed_policy_path, - MacPreferences* preferences) - : AsyncPolicyLoader(task_runner), - preferences_(preferences), - managed_policy_path_(managed_policy_path) {} - -PolicyLoaderMac::~PolicyLoaderMac() {} - -void PolicyLoaderMac::InitOnBackgroundThread() { - if (!managed_policy_path_.empty()) { - watcher_.Watch( - managed_policy_path_, false, - base::Bind(&PolicyLoaderMac::OnFileUpdated, base::Unretained(this))); - } -} - -scoped_ptr<PolicyBundle> PolicyLoaderMac::Load() { - preferences_->AppSynchronize(kCFPreferencesCurrentApplication); - scoped_ptr<PolicyBundle> bundle(new PolicyBundle()); - - // Load Chrome's policy. - PolicyMap& chrome_policy = - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - - PolicyLoadStatusSample status; - bool policy_present = false; - const Schema* schema = - schema_map()->GetSchema(PolicyNamespace(POLICY_DOMAIN_CHROME, "")); - for (Schema::Iterator it = schema->GetPropertiesIterator(); - !it.IsAtEnd(); it.Advance()) { - base::ScopedCFTypeRef<CFStringRef> name( - base::SysUTF8ToCFStringRef(it.key())); - base::ScopedCFTypeRef<CFPropertyListRef> value( - preferences_->CopyAppValue(name, kCFPreferencesCurrentApplication)); - if (!value.get()) - continue; - policy_present = true; - bool forced = - preferences_->AppValueIsForced(name, kCFPreferencesCurrentApplication); - PolicyLevel level = forced ? POLICY_LEVEL_MANDATORY : - POLICY_LEVEL_RECOMMENDED; - // TODO(joaodasilva): figure the policy scope. - base::Value* policy = CreateValueFromProperty(value); - if (policy) - chrome_policy.Set(it.key(), level, POLICY_SCOPE_USER, policy, NULL); - else - status.Add(POLICY_LOAD_STATUS_PARSE_ERROR); - } - - if (!policy_present) - status.Add(POLICY_LOAD_STATUS_NO_POLICY); - - // Load policy for the registered components. - LoadPolicyForDomain(POLICY_DOMAIN_EXTENSIONS, "extensions", bundle.get()); - - return bundle.Pass(); -} - -base::Time PolicyLoaderMac::LastModificationTime() { - base::PlatformFileInfo file_info; - if (!base::GetFileInfo(managed_policy_path_, &file_info) || - file_info.is_directory) { - return base::Time(); - } - - return file_info.last_modified; -} - -// static -base::Value* PolicyLoaderMac::CreateValueFromProperty( - CFPropertyListRef property) { - if (CFCast<CFNullRef>(property)) - return base::Value::CreateNullValue(); - - if (CFBooleanRef boolean = CFCast<CFBooleanRef>(property)) - return base::Value::CreateBooleanValue(CFBooleanGetValue(boolean)); - - if (CFNumberRef number = CFCast<CFNumberRef>(property)) { - // CFNumberGetValue() converts values implicitly when the conversion is not - // lossy. Check the type before trying to convert. - if (CFNumberIsFloatType(number)) { - double double_value; - if (CFNumberGetValue(number, kCFNumberDoubleType, &double_value)) - return base::Value::CreateDoubleValue(double_value); - } else { - int int_value; - if (CFNumberGetValue(number, kCFNumberIntType, &int_value)) - return base::Value::CreateIntegerValue(int_value); - } - } - - if (CFStringRef string = CFCast<CFStringRef>(property)) - return base::Value::CreateStringValue(base::SysCFStringRefToUTF8(string)); - - if (CFDictionaryRef dict = CFCast<CFDictionaryRef>(property)) { - base::DictionaryValue* dict_value = new base::DictionaryValue(); - CFDictionaryApplyFunction(dict, DictionaryEntryToValue, dict_value); - return dict_value; - } - - if (CFArrayRef array = CFCast<CFArrayRef>(property)) { - base::ListValue* list_value = new base::ListValue(); - CFArrayApplyFunction(array, - CFRangeMake(0, CFArrayGetCount(array)), - ArrayEntryToValue, - list_value); - return list_value; - } - - return NULL; -} - -void PolicyLoaderMac::LoadPolicyForDomain( - PolicyDomain domain, - const std::string& domain_name, - PolicyBundle* bundle) { - std::string id_prefix(base::mac::BaseBundleID()); - id_prefix.append(".").append(domain_name).append("."); - - const ComponentMap* components = schema_map()->GetComponents(domain); - if (!components) - return; - - for (ComponentMap::const_iterator it = components->begin(); - it != components->end(); ++it) { - PolicyMap policy; - LoadPolicyForComponent(id_prefix + it->first, it->second, &policy); - if (!policy.empty()) - bundle->Get(PolicyNamespace(domain, it->first)).Swap(&policy); - } -} - -void PolicyLoaderMac::LoadPolicyForComponent( - const std::string& bundle_id_string, - const Schema& schema, - PolicyMap* policy) { - // TODO(joaodasilva): Extensions may be registered in a ComponentMap - // without a schema, to allow a graceful update of the Legacy Browser Support - // extension on Windows. Remove this check once that support is removed. - if (!schema.valid()) - return; - - base::ScopedCFTypeRef<CFStringRef> bundle_id( - base::SysUTF8ToCFStringRef(bundle_id_string)); - preferences_->AppSynchronize(bundle_id); - - for (Schema::Iterator it = schema.GetPropertiesIterator(); - !it.IsAtEnd(); it.Advance()) { - base::ScopedCFTypeRef<CFStringRef> pref_name( - base::SysUTF8ToCFStringRef(it.key())); - base::ScopedCFTypeRef<CFPropertyListRef> value( - preferences_->CopyAppValue(pref_name, bundle_id)); - if (!value.get()) - continue; - bool forced = - preferences_->AppValueIsForced(pref_name, bundle_id); - PolicyLevel level = forced ? POLICY_LEVEL_MANDATORY : - POLICY_LEVEL_RECOMMENDED; - scoped_ptr<base::Value> policy_value(CreateValueFromProperty(value)); - if (policy_value) { - policy->Set(it.key(), level, POLICY_SCOPE_USER, - policy_value.release(), NULL); - } - } -} - -void PolicyLoaderMac::OnFileUpdated(const base::FilePath& path, bool error) { - if (!error) - Reload(false); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_loader_mac.h b/chrome/browser/policy/policy_loader_mac.h deleted file mode 100644 index 93063a0..0000000 --- a/chrome/browser/policy/policy_loader_mac.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_LOADER_MAC_H_ -#define CHROME_BROWSER_POLICY_POLICY_LOADER_MAC_H_ - -#include <string> - -#include <CoreFoundation/CoreFoundation.h> - -#include "base/files/file_path.h" -#include "base/files/file_path_watcher.h" -#include "base/memory/ref_counted.h" -#include "components/policy/core/common/async_policy_loader.h" -#include "components/policy/core/common/policy_namespace.h" - -class MacPreferences; - -namespace base { -class SequencedTaskRunner; -class Value; -} // namespace base - -namespace policy { - -class PolicyBundle; -class PolicyMap; -class Schema; - -// A policy loader that loads policies from the Mac preferences system, and -// watches the managed preferences files for updates. -class PolicyLoaderMac : public AsyncPolicyLoader { - public: - PolicyLoaderMac(scoped_refptr<base::SequencedTaskRunner> task_runner, - const base::FilePath& managed_policy_path, - MacPreferences* preferences); - virtual ~PolicyLoaderMac(); - - // AsyncPolicyLoader implementation. - virtual void InitOnBackgroundThread() OVERRIDE; - virtual scoped_ptr<PolicyBundle> Load() OVERRIDE; - virtual base::Time LastModificationTime() OVERRIDE; - - // Converts a CFPropertyListRef to the equivalent base::Value. CFDictionary - // entries whose key is not a CFStringRef are ignored. - // The returned value is owned by the caller. - // Returns NULL if an invalid CFType was found, such as CFDate or CFData. - static base::Value* CreateValueFromProperty(CFPropertyListRef property); - - private: - // Callback for the FilePathWatcher. - void OnFileUpdated(const base::FilePath& path, bool error); - - // Loads policies for the components described in the current schema_map() - // which belong to the domain |domain_name|, and stores them in the |bundle|. - void LoadPolicyForDomain( - PolicyDomain domain, - const std::string& domain_name, - PolicyBundle* bundle); - - // Loads the policies described in |schema| from the bundle identified by - // |bundle_id_string|, and stores them in |policy|. - void LoadPolicyForComponent(const std::string& bundle_id_string, - const Schema& schema, - PolicyMap* policy); - - scoped_ptr<MacPreferences> preferences_; - - // Path to the managed preferences file for the current user, if it could - // be found. Updates of this file trigger a policy reload. - base::FilePath managed_policy_path_; - - // Watches for events on the |managed_policy_path_|. - base::FilePathWatcher watcher_; - - DISALLOW_COPY_AND_ASSIGN(PolicyLoaderMac); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_LOADER_MAC_H_ diff --git a/chrome/browser/policy/policy_loader_mac_unittest.cc b/chrome/browser/policy/policy_loader_mac_unittest.cc deleted file mode 100644 index 5445447..0000000 --- a/chrome/browser/policy/policy_loader_mac_unittest.cc +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <CoreFoundation/CoreFoundation.h> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/mac/scoped_cftyperef.h" -#include "base/strings/sys_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/policy/policy_loader_mac.h" -#include "components/policy/core/common/async_policy_provider.h" -#include "components/policy/core/common/configuration_policy_provider_test.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/preferences_mock_mac.h" -#include "testing/gtest/include/gtest/gtest.h" - -using base::ScopedCFTypeRef; - -namespace policy { - -namespace { - -// Converts a base::Value to the equivalent CFPropertyListRef. -// The returned value is owned by the caller. -CFPropertyListRef CreatePropertyFromValue(const base::Value* value) { - switch (value->GetType()) { - case base::Value::TYPE_NULL: - return kCFNull; - - case base::Value::TYPE_BOOLEAN: { - bool bool_value; - if (value->GetAsBoolean(&bool_value)) - return bool_value ? kCFBooleanTrue : kCFBooleanFalse; - break; - } - - case base::Value::TYPE_INTEGER: { - int int_value; - if (value->GetAsInteger(&int_value)) { - return CFNumberCreate( - kCFAllocatorDefault, kCFNumberIntType, &int_value); - } - break; - } - - case base::Value::TYPE_DOUBLE: { - double double_value; - if (value->GetAsDouble(&double_value)) { - return CFNumberCreate( - kCFAllocatorDefault, kCFNumberDoubleType, &double_value); - } - break; - } - - case base::Value::TYPE_STRING: { - std::string string_value; - if (value->GetAsString(&string_value)) - return base::SysUTF8ToCFStringRef(string_value); - break; - } - - case base::Value::TYPE_DICTIONARY: { - const base::DictionaryValue* dict_value; - if (value->GetAsDictionary(&dict_value)) { - // |dict| is owned by the caller. - CFMutableDictionaryRef dict = - CFDictionaryCreateMutable(kCFAllocatorDefault, - dict_value->size(), - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); - for (base::DictionaryValue::Iterator iterator(*dict_value); - !iterator.IsAtEnd(); iterator.Advance()) { - // CFDictionaryAddValue() retains both |key| and |value|, so make sure - // the references are balanced. - ScopedCFTypeRef<CFStringRef> key( - base::SysUTF8ToCFStringRef(iterator.key())); - ScopedCFTypeRef<CFPropertyListRef> cf_value( - CreatePropertyFromValue(&iterator.value())); - if (cf_value) - CFDictionaryAddValue(dict, key, cf_value); - } - return dict; - } - break; - } - - case base::Value::TYPE_LIST: { - const base::ListValue* list; - if (value->GetAsList(&list)) { - CFMutableArrayRef array = - CFArrayCreateMutable(NULL, list->GetSize(), &kCFTypeArrayCallBacks); - for (base::ListValue::const_iterator it(list->begin()); - it != list->end(); ++it) { - // CFArrayAppendValue() retains |value|, so make sure the reference - // created by CreatePropertyFromValue() is released. - ScopedCFTypeRef<CFPropertyListRef> cf_value( - CreatePropertyFromValue(*it)); - if (cf_value) - CFArrayAppendValue(array, cf_value); - } - return array; - } - break; - } - - case base::Value::TYPE_BINARY: - // This type isn't converted (though it can be represented as CFData) - // because there's no equivalent JSON type, and policy values can only - // take valid JSON values. - break; - } - - return NULL; -} - -class TestHarness : public PolicyProviderTestHarness { - public: - TestHarness(); - virtual ~TestHarness(); - - virtual void SetUp() OVERRIDE; - - virtual ConfigurationPolicyProvider* CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE; - - virtual void InstallEmptyPolicy() OVERRIDE; - virtual void InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) OVERRIDE; - virtual void InstallIntegerPolicy(const std::string& policy_name, - int policy_value) OVERRIDE; - virtual void InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) OVERRIDE; - virtual void InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) OVERRIDE; - virtual void InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) OVERRIDE; - - static PolicyProviderTestHarness* Create(); - - private: - MockPreferences* prefs_; - - DISALLOW_COPY_AND_ASSIGN(TestHarness); -}; - -TestHarness::TestHarness() - : PolicyProviderTestHarness(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER) {} - -TestHarness::~TestHarness() {} - -void TestHarness::SetUp() {} - -ConfigurationPolicyProvider* TestHarness::CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) { - prefs_ = new MockPreferences(); - scoped_ptr<AsyncPolicyLoader> loader( - new PolicyLoaderMac(task_runner, base::FilePath(), prefs_)); - return new AsyncPolicyProvider(registry, loader.Pass()); -} - -void TestHarness::InstallEmptyPolicy() {} - -void TestHarness::InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) { - ScopedCFTypeRef<CFStringRef> name(base::SysUTF8ToCFStringRef(policy_name)); - ScopedCFTypeRef<CFStringRef> value(base::SysUTF8ToCFStringRef(policy_value)); - prefs_->AddTestItem(name, value, true); -} - -void TestHarness::InstallIntegerPolicy(const std::string& policy_name, - int policy_value) { - ScopedCFTypeRef<CFStringRef> name(base::SysUTF8ToCFStringRef(policy_name)); - ScopedCFTypeRef<CFNumberRef> value( - CFNumberCreate(NULL, kCFNumberIntType, &policy_value)); - prefs_->AddTestItem(name, value, true); -} - -void TestHarness::InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) { - ScopedCFTypeRef<CFStringRef> name(base::SysUTF8ToCFStringRef(policy_name)); - prefs_->AddTestItem(name, - policy_value ? kCFBooleanTrue : kCFBooleanFalse, - true); -} - -void TestHarness::InstallStringListPolicy(const std::string& policy_name, - const base::ListValue* policy_value) { - ScopedCFTypeRef<CFStringRef> name(base::SysUTF8ToCFStringRef(policy_name)); - ScopedCFTypeRef<CFPropertyListRef> array( - CreatePropertyFromValue(policy_value)); - ASSERT_TRUE(array); - prefs_->AddTestItem(name, array, true); -} - -void TestHarness::InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) { - ScopedCFTypeRef<CFStringRef> name(base::SysUTF8ToCFStringRef(policy_name)); - ScopedCFTypeRef<CFPropertyListRef> dict( - CreatePropertyFromValue(policy_value)); - ASSERT_TRUE(dict); - prefs_->AddTestItem(name, dict, true); -} - -// static -PolicyProviderTestHarness* TestHarness::Create() { - return new TestHarness(); -} - -} // namespace - -// Instantiate abstract test case for basic policy reading tests. -INSTANTIATE_TEST_CASE_P( - PolicyProviderMacTest, - ConfigurationPolicyProviderTest, - testing::Values(TestHarness::Create)); - -// TODO(joaodasilva): instantiate Configuration3rdPartyPolicyProviderTest too -// once the mac loader supports 3rd party policy. http://crbug.com/108995 - -// Special test cases for some mac preferences details. -class PolicyLoaderMacTest : public PolicyTestBase { - protected: - PolicyLoaderMacTest() - : prefs_(new MockPreferences()) {} - virtual ~PolicyLoaderMacTest() {} - - virtual void SetUp() OVERRIDE { - PolicyTestBase::SetUp(); - scoped_ptr<AsyncPolicyLoader> loader(new PolicyLoaderMac( - loop_.message_loop_proxy(), base::FilePath(), prefs_)); - provider_.reset(new AsyncPolicyProvider(&schema_registry_, loader.Pass())); - provider_->Init(&schema_registry_); - } - - virtual void TearDown() OVERRIDE { - provider_->Shutdown(); - PolicyTestBase::TearDown(); - } - - MockPreferences* prefs_; - scoped_ptr<AsyncPolicyProvider> provider_; -}; - -TEST_F(PolicyLoaderMacTest, Invalid) { - ScopedCFTypeRef<CFStringRef> name( - base::SysUTF8ToCFStringRef(test_keys::kKeyString)); - const char buffer[] = "binary \xde\xad\xbe\xef data"; - ScopedCFTypeRef<CFDataRef> invalid_data( - CFDataCreate(kCFAllocatorDefault, - reinterpret_cast<const UInt8 *>(buffer), - arraysize(buffer))); - ASSERT_TRUE(invalid_data); - prefs_->AddTestItem(name, invalid_data.get(), true); - prefs_->AddTestItem(name, invalid_data.get(), false); - - // Make the provider read the updated |prefs_|. - provider_->RefreshPolicies(); - loop_.RunUntilIdle(); - const PolicyBundle kEmptyBundle; - EXPECT_TRUE(provider_->policies().Equals(kEmptyBundle)); -} - -TEST_F(PolicyLoaderMacTest, TestNonForcedValue) { - ScopedCFTypeRef<CFStringRef> name( - base::SysUTF8ToCFStringRef(test_keys::kKeyString)); - ScopedCFTypeRef<CFPropertyListRef> test_value( - base::SysUTF8ToCFStringRef("string value")); - ASSERT_TRUE(test_value.get()); - prefs_->AddTestItem(name, test_value.get(), false); - - // Make the provider read the updated |prefs_|. - provider_->RefreshPolicies(); - loop_.RunUntilIdle(); - PolicyBundle expected_bundle; - expected_bundle.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .Set(test_keys::kKeyString, - POLICY_LEVEL_RECOMMENDED, - POLICY_SCOPE_USER, - base::Value::CreateStringValue("string value"), - NULL); - EXPECT_TRUE(provider_->policies().Equals(expected_bundle)); -} - -TEST_F(PolicyLoaderMacTest, TestConversions) { - base::DictionaryValue root; - - // base::Value::TYPE_NULL - root.Set("null", base::Value::CreateNullValue()); - - // base::Value::TYPE_BOOLEAN - root.SetBoolean("false", false); - root.SetBoolean("true", true); - - // base::Value::TYPE_INTEGER - root.SetInteger("int", 123); - root.SetInteger("zero", 0); - - // base::Value::TYPE_DOUBLE - root.SetDouble("double", 123.456); - root.SetDouble("zerod", 0.0); - - // base::Value::TYPE_STRING - root.SetString("string", "the fox jumps over something"); - root.SetString("empty", ""); - - // base::Value::TYPE_LIST - base::ListValue list; - root.Set("emptyl", list.DeepCopy()); - for (base::DictionaryValue::Iterator it(root); !it.IsAtEnd(); it.Advance()) - list.Append(it.value().DeepCopy()); - EXPECT_EQ(root.size(), list.GetSize()); - list.Append(root.DeepCopy()); - root.Set("list", list.DeepCopy()); - - // base::Value::TYPE_DICTIONARY - base::DictionaryValue dict; - root.Set("emptyd", dict.DeepCopy()); - // Very meta. - root.Set("dict", root.DeepCopy()); - - ScopedCFTypeRef<CFPropertyListRef> property(CreatePropertyFromValue(&root)); - ASSERT_TRUE(property); - scoped_ptr<base::Value> value( - PolicyLoaderMac::CreateValueFromProperty(property)); - ASSERT_TRUE(value.get()); - - EXPECT_TRUE(root.Equals(value.get())); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_loader_win.cc b/chrome/browser/policy/policy_loader_win.cc deleted file mode 100644 index 8d89206..0000000 --- a/chrome/browser/policy/policy_loader_win.cc +++ /dev/null @@ -1,549 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_loader_win.h" - -#include <windows.h> -#include <rpc.h> // For struct GUID -#include <shlwapi.h> // For PathIsUNC() -#include <userenv.h> // For GPO functions - -#include <string> -#include <vector> - -// shlwapi.dll is required for PathIsUNC(). -#pragma comment(lib, "shlwapi.lib") -// userenv.dll is required for various GPO functions. -#pragma comment(lib, "userenv.lib") - -#include "base/basictypes.h" -#include "base/file_util.h" -#include "base/json/json_reader.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/scoped_native_library.h" -#include "base/sequenced_task_runner.h" -#include "base/stl_util.h" -#include "base/strings/string16.h" -#include "base/strings/string_util.h" -#include "chrome/browser/policy/policy_load_status.h" -#include "chrome/browser/policy/preg_parser_win.h" -#include "components/json_schema/json_schema_constants.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_namespace.h" -#include "components/policy/core/common/registry_dict_win.h" -#include "components/policy/core/common/schema.h" - -namespace schema = json_schema_constants; - -namespace policy { - -namespace { - -const char kKeyMandatory[] = "policy"; -const char kKeyRecommended[] = "recommended"; -const char kKeySchema[] = "schema"; -const char kKeyThirdParty[] = "3rdparty"; - -// The GUID of the registry settings group policy extension. -GUID kRegistrySettingsCSEGUID = REGISTRY_EXTENSION_GUID; - -// A helper class encapsulating run-time-linked function calls to Wow64 APIs. -class Wow64Functions { - public: - Wow64Functions() - : kernel32_lib_(base::FilePath(L"kernel32")), - is_wow_64_process_(NULL), - wow_64_disable_wow_64_fs_redirection_(NULL), - wow_64_revert_wow_64_fs_redirection_(NULL) { - if (kernel32_lib_.is_valid()) { - is_wow_64_process_ = reinterpret_cast<IsWow64Process>( - kernel32_lib_.GetFunctionPointer("IsWow64Process")); - wow_64_disable_wow_64_fs_redirection_ = - reinterpret_cast<Wow64DisableWow64FSRedirection>( - kernel32_lib_.GetFunctionPointer( - "Wow64DisableWow64FsRedirection")); - wow_64_revert_wow_64_fs_redirection_ = - reinterpret_cast<Wow64RevertWow64FSRedirection>( - kernel32_lib_.GetFunctionPointer( - "Wow64RevertWow64FsRedirection")); - } - } - - bool is_valid() { - return is_wow_64_process_ && - wow_64_disable_wow_64_fs_redirection_ && - wow_64_revert_wow_64_fs_redirection_; - } - - bool IsWow64() { - BOOL result = 0; - if (!is_wow_64_process_(GetCurrentProcess(), &result)) - PLOG(WARNING) << "IsWow64ProcFailed"; - return !!result; - } - - bool DisableFsRedirection(PVOID* previous_state) { - return !!wow_64_disable_wow_64_fs_redirection_(previous_state); - } - - bool RevertFsRedirection(PVOID previous_state) { - return !!wow_64_revert_wow_64_fs_redirection_(previous_state); - } - - private: - typedef BOOL (WINAPI* IsWow64Process)(HANDLE, PBOOL); - typedef BOOL (WINAPI* Wow64DisableWow64FSRedirection)(PVOID*); - typedef BOOL (WINAPI* Wow64RevertWow64FSRedirection)(PVOID); - - base::ScopedNativeLibrary kernel32_lib_; - - IsWow64Process is_wow_64_process_; - Wow64DisableWow64FSRedirection wow_64_disable_wow_64_fs_redirection_; - Wow64RevertWow64FSRedirection wow_64_revert_wow_64_fs_redirection_; - - DISALLOW_COPY_AND_ASSIGN(Wow64Functions); -}; - -// Global Wow64Function instance used by ScopedDisableWow64Redirection below. -static base::LazyInstance<Wow64Functions> g_wow_64_functions = - LAZY_INSTANCE_INITIALIZER; - -// Scoper that switches off Wow64 File System Redirection during its lifetime. -class ScopedDisableWow64Redirection { - public: - ScopedDisableWow64Redirection() - : active_(false), - previous_state_(NULL) { - Wow64Functions* wow64 = g_wow_64_functions.Pointer(); - if (wow64->is_valid() && wow64->IsWow64()) { - if (wow64->DisableFsRedirection(&previous_state_)) - active_ = true; - else - PLOG(WARNING) << "Wow64DisableWow64FSRedirection"; - } - } - - ~ScopedDisableWow64Redirection() { - if (active_) - CHECK(g_wow_64_functions.Get().RevertFsRedirection(previous_state_)); - } - - bool is_active() { return active_; } - - private: - bool active_; - PVOID previous_state_; - - DISALLOW_COPY_AND_ASSIGN(ScopedDisableWow64Redirection); -}; - -// AppliedGPOListProvider implementation that calls actual Windows APIs. -class WinGPOListProvider : public AppliedGPOListProvider { - public: - virtual ~WinGPOListProvider() {} - - // AppliedGPOListProvider: - virtual DWORD GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) OVERRIDE { - return ::GetAppliedGPOList(flags, machine_name, sid_user, extension_guid, - gpo_list); - } - - virtual BOOL FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) OVERRIDE { - return ::FreeGPOList(gpo_list); - } -}; - -// The default windows GPO list provider used for PolicyLoaderWin. -static base::LazyInstance<WinGPOListProvider> g_win_gpo_list_provider = - LAZY_INSTANCE_INITIALIZER; - -std::string GetSchemaTypeForValueType(base::Value::Type value_type) { - switch (value_type) { - case base::Value::TYPE_DICTIONARY: - return json_schema_constants::kObject; - case base::Value::TYPE_INTEGER: - return json_schema_constants::kInteger; - case base::Value::TYPE_LIST: - return json_schema_constants::kArray; - case base::Value::TYPE_BOOLEAN: - return json_schema_constants::kBoolean; - case base::Value::TYPE_STRING: - return json_schema_constants::kString; - default: - break; - } - - NOTREACHED() << "Unsupported policy value type " << value_type; - return json_schema_constants::kNull; -} - -// Parses |gpo_dict| according to |schema| and writes the resulting policy -// settings to |policy| for the given |scope| and |level|. -void ParsePolicy(const RegistryDict* gpo_dict, - PolicyLevel level, - PolicyScope scope, - const base::DictionaryValue* schema, - PolicyMap* policy) { - if (!gpo_dict) - return; - - scoped_ptr<base::Value> policy_value(gpo_dict->ConvertToJSON(schema)); - const base::DictionaryValue* policy_dict = NULL; - if (!policy_value->GetAsDictionary(&policy_dict) || !policy_dict) { - LOG(WARNING) << "Root policy object is not a dictionary!"; - return; - } - - policy->LoadFrom(policy_dict, level, scope); -} - -} // namespace - -const base::FilePath::CharType PolicyLoaderWin::kPRegFileName[] = - FILE_PATH_LITERAL("Registry.pol"); - -PolicyLoaderWin::PolicyLoaderWin( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const string16& chrome_policy_key, - AppliedGPOListProvider* gpo_provider) - : AsyncPolicyLoader(task_runner), - is_initialized_(false), - chrome_policy_key_(chrome_policy_key), - gpo_provider_(gpo_provider), - user_policy_changed_event_(false, false), - machine_policy_changed_event_(false, false), - user_policy_watcher_failed_(false), - machine_policy_watcher_failed_(false) { - if (!::RegisterGPNotification(user_policy_changed_event_.handle(), false)) { - DPLOG(WARNING) << "Failed to register user group policy notification"; - user_policy_watcher_failed_ = true; - } - if (!::RegisterGPNotification(machine_policy_changed_event_.handle(), true)) { - DPLOG(WARNING) << "Failed to register machine group policy notification."; - machine_policy_watcher_failed_ = true; - } -} - -PolicyLoaderWin::~PolicyLoaderWin() { - if (!user_policy_watcher_failed_) { - ::UnregisterGPNotification(user_policy_changed_event_.handle()); - user_policy_watcher_.StopWatching(); - } - if (!machine_policy_watcher_failed_) { - ::UnregisterGPNotification(machine_policy_changed_event_.handle()); - machine_policy_watcher_.StopWatching(); - } -} - -// static -scoped_ptr<PolicyLoaderWin> PolicyLoaderWin::Create( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const string16& chrome_policy_key) { - return make_scoped_ptr( - new PolicyLoaderWin(task_runner, - chrome_policy_key, - g_win_gpo_list_provider.Pointer())); -} - -void PolicyLoaderWin::InitOnBackgroundThread() { - is_initialized_ = true; - SetupWatches(); -} - -scoped_ptr<PolicyBundle> PolicyLoaderWin::Load() { - // Reset the watches BEFORE reading the individual policies to avoid - // missing a change notification. - if (is_initialized_) - SetupWatches(); - - if (chrome_policy_schema_.empty()) - BuildChromePolicySchema(); - - // Policy scope and corresponding hive. - static const struct { - PolicyScope scope; - HKEY hive; - } kScopes[] = { - { POLICY_SCOPE_MACHINE, HKEY_LOCAL_MACHINE }, - { POLICY_SCOPE_USER, HKEY_CURRENT_USER }, - }; - - // Load policy data for the different scopes/levels and merge them. - scoped_ptr<PolicyBundle> bundle(new PolicyBundle()); - PolicyMap* chrome_policy = - &bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - for (size_t i = 0; i < arraysize(kScopes); ++i) { - PolicyScope scope = kScopes[i].scope; - PolicyLoadStatusSample status; - RegistryDict gpo_dict; - - // Note: GPO rules mandate a call to EnterCriticalPolicySection() here, and - // a matching LeaveCriticalPolicySection() call below after the - // ReadPolicyFromGPO() block. Unfortunately, the policy mutex may be - // unavailable for extended periods of time, and there are reports of this - // happening in the wild: http://crbug.com/265862. - // - // Blocking for minutes is neither acceptable for Chrome startup, nor on - // the FILE thread on which this code runs in steady state. Given that - // there have never been any reports of issues due to partially-applied / - // corrupt group policy, this code intentionally omits the - // EnterCriticalPolicySection() call. - // - // If there's ever reason to revisit this decision, one option could be to - // make the EnterCriticalPolicySection() call on a dedicated thread and - // timeout on it more aggressively. For now, there's no justification for - // the additional effort this would introduce. - - if (!ReadPolicyFromGPO(scope, &gpo_dict, &status)) { - VLOG(1) << "Failed to read GPO files for " << scope - << " falling back to registry."; - gpo_dict.ReadRegistry(kScopes[i].hive, chrome_policy_key_); - } - - // Remove special-cased entries from the GPO dictionary. - scoped_ptr<RegistryDict> recommended_dict( - gpo_dict.RemoveKey(kKeyRecommended)); - scoped_ptr<RegistryDict> third_party_dict( - gpo_dict.RemoveKey(kKeyThirdParty)); - - // Load Chrome policy. - LoadChromePolicy(&gpo_dict, POLICY_LEVEL_MANDATORY, scope, chrome_policy); - LoadChromePolicy(recommended_dict.get(), POLICY_LEVEL_RECOMMENDED, scope, - chrome_policy); - - // Load 3rd-party policy. - if (third_party_dict) - Load3rdPartyPolicy(third_party_dict.get(), scope, bundle.get()); - } - - return bundle.Pass(); -} - -void PolicyLoaderWin::BuildChromePolicySchema() { - // TODO(joaodasilva): use the Schema directly instead of building this - // DictionaryValue. - scoped_ptr<base::DictionaryValue> properties(new base::DictionaryValue()); - const Schema* chrome_schema = - schema_map()->GetSchema(PolicyNamespace(POLICY_DOMAIN_CHROME, "")); - for (Schema::Iterator it = chrome_schema->GetPropertiesIterator(); - !it.IsAtEnd(); it.Advance()) { - const std::string schema_type = - GetSchemaTypeForValueType(it.schema().type()); - scoped_ptr<base::DictionaryValue> entry_schema(new base::DictionaryValue()); - entry_schema->SetStringWithoutPathExpansion(json_schema_constants::kType, - schema_type); - - if (it.schema().type() == base::Value::TYPE_LIST) { - scoped_ptr<base::DictionaryValue> items_schema( - new base::DictionaryValue()); - items_schema->SetStringWithoutPathExpansion( - json_schema_constants::kType, json_schema_constants::kString); - entry_schema->SetWithoutPathExpansion(json_schema_constants::kItems, - items_schema.release()); - } - properties->SetWithoutPathExpansion(it.key(), entry_schema.release()); - } - chrome_policy_schema_.SetStringWithoutPathExpansion( - json_schema_constants::kType, json_schema_constants::kObject); - chrome_policy_schema_.SetWithoutPathExpansion( - json_schema_constants::kProperties, properties.release()); -} - -bool PolicyLoaderWin::ReadPRegFile(const base::FilePath& preg_file, - RegistryDict* policy, - PolicyLoadStatusSample* status) { - // The following deals with the minor annoyance that Wow64 FS redirection - // might need to be turned off: This is the case if running as a 32-bit - // process on a 64-bit system, in which case Wow64 FS redirection redirects - // access to the %WINDIR%/System32/GroupPolicy directory to - // %WINDIR%/SysWOW64/GroupPolicy, but the file is actually in the - // system-native directory. - if (base::PathExists(preg_file)) { - return preg_parser::ReadFile(preg_file, chrome_policy_key_, policy, status); - } else { - // Try with redirection switched off. - ScopedDisableWow64Redirection redirection_disable; - if (redirection_disable.is_active() && base::PathExists(preg_file)) { - status->Add(POLICY_LOAD_STATUS_WOW64_REDIRECTION_DISABLED); - return preg_parser::ReadFile(preg_file, chrome_policy_key_, policy, - status); - } - } - - // Report the error. - LOG(ERROR) << "PReg file doesn't exist: " << preg_file.value(); - status->Add(POLICY_LOAD_STATUS_MISSING); - return false; -} - -bool PolicyLoaderWin::LoadGPOPolicy(PolicyScope scope, - PGROUP_POLICY_OBJECT policy_object_list, - RegistryDict* policy, - PolicyLoadStatusSample* status) { - RegistryDict parsed_policy; - RegistryDict forced_policy; - for (GROUP_POLICY_OBJECT* policy_object = policy_object_list; - policy_object; policy_object = policy_object->pNext) { - if (policy_object->dwOptions & GPO_FLAG_DISABLE) - continue; - - if (PathIsUNC(policy_object->lpFileSysPath)) { - // UNC path: Assume this is an AD-managed machine, which updates the - // registry via GPO's standard registry CSE periodically. Fall back to - // reading from the registry in this case. - status->Add(POLICY_LOAD_STATUS_INACCCESSIBLE); - return false; - } - - base::FilePath preg_file_path( - base::FilePath(policy_object->lpFileSysPath).Append(kPRegFileName)); - if (policy_object->dwOptions & GPO_FLAG_FORCE) { - RegistryDict new_forced_policy; - if (!ReadPRegFile(preg_file_path, &new_forced_policy, status)) - return false; - - // Merge with existing forced policy, giving precedence to the existing - // forced policy. - new_forced_policy.Merge(forced_policy); - forced_policy.Swap(&new_forced_policy); - } else { - if (!ReadPRegFile(preg_file_path, &parsed_policy, status)) - return false; - } - } - - // Merge, give precedence to forced policy. - parsed_policy.Merge(forced_policy); - policy->Swap(&parsed_policy); - - return true; -} - -bool PolicyLoaderWin::ReadPolicyFromGPO(PolicyScope scope, - RegistryDict* policy, - PolicyLoadStatusSample* status) { - PGROUP_POLICY_OBJECT policy_object_list = NULL; - DWORD flags = scope == POLICY_SCOPE_MACHINE ? GPO_LIST_FLAG_MACHINE : 0; - if (gpo_provider_->GetAppliedGPOList( - flags, NULL, NULL, &kRegistrySettingsCSEGUID, - &policy_object_list) != ERROR_SUCCESS) { - PLOG(ERROR) << "GetAppliedGPOList scope " << scope; - status->Add(POLICY_LOAD_STATUS_QUERY_FAILED); - return false; - } - - bool result = true; - if (policy_object_list) { - result = LoadGPOPolicy(scope, policy_object_list, policy, status); - if (!gpo_provider_->FreeGPOList(policy_object_list)) - LOG(WARNING) << "FreeGPOList"; - } else { - status->Add(POLICY_LOAD_STATUS_NO_POLICY); - } - - return result; -} - -void PolicyLoaderWin::LoadChromePolicy(const RegistryDict* gpo_dict, - PolicyLevel level, - PolicyScope scope, - PolicyMap* chrome_policy_map) { - PolicyMap policy; - ParsePolicy(gpo_dict, level, scope, &chrome_policy_schema_, &policy); - chrome_policy_map->MergeFrom(policy); -} - -void PolicyLoaderWin::Load3rdPartyPolicy(const RegistryDict* gpo_dict, - PolicyScope scope, - PolicyBundle* bundle) { - // Map of known 3rd party policy domain name to their enum values. - static const struct { - const char* name; - PolicyDomain domain; - } k3rdPartyDomains[] = { - { "extensions", POLICY_DOMAIN_EXTENSIONS }, - }; - - // Policy level and corresponding path. - static const struct { - PolicyLevel level; - const char* path; - } kLevels[] = { - { POLICY_LEVEL_MANDATORY, kKeyMandatory }, - { POLICY_LEVEL_RECOMMENDED, kKeyRecommended }, - }; - - for (size_t i = 0; i < arraysize(k3rdPartyDomains); i++) { - const char* name = k3rdPartyDomains[i].name; - const PolicyDomain domain = k3rdPartyDomains[i].domain; - const RegistryDict* domain_dict = gpo_dict->GetKey(name); - if (!domain_dict) - continue; - - for (RegistryDict::KeyMap::const_iterator component( - domain_dict->keys().begin()); - component != domain_dict->keys().end(); - ++component) { - // Load the schema. - const base::DictionaryValue* schema_dict = NULL; - scoped_ptr<base::Value> schema; - std::string schema_json; - const base::Value* schema_value = component->second->GetValue(kKeySchema); - if (schema_value && schema_value->GetAsString(&schema_json)) { - schema.reset(base::JSONReader::Read(schema_json)); - if (!schema || !schema->GetAsDictionary(&schema_dict)) { - LOG(WARNING) << "Failed to parse 3rd-part policy schema for " - << domain << "/" << component->first; - } - } - - // Parse policy. - for (size_t j = 0; j < arraysize(kLevels); j++) { - const RegistryDict* policy_dict = - component->second->GetKey(kLevels[j].path); - if (!policy_dict) - continue; - - PolicyMap policy; - ParsePolicy(policy_dict, kLevels[j].level, scope, schema_dict, &policy); - PolicyNamespace policy_namespace(domain, component->first); - bundle->Get(policy_namespace).MergeFrom(policy); - } - } - } -} - -void PolicyLoaderWin::SetupWatches() { - DCHECK(is_initialized_); - if (!user_policy_watcher_failed_ && - !user_policy_watcher_.GetWatchedObject() && - !user_policy_watcher_.StartWatching( - user_policy_changed_event_.handle(), this)) { - DLOG(WARNING) << "Failed to start watch for user policy change event"; - user_policy_watcher_failed_ = true; - } - if (!machine_policy_watcher_failed_ && - !machine_policy_watcher_.GetWatchedObject() && - !machine_policy_watcher_.StartWatching( - machine_policy_changed_event_.handle(), this)) { - DLOG(WARNING) << "Failed to start watch for machine policy change event"; - machine_policy_watcher_failed_ = true; - } -} - -void PolicyLoaderWin::OnObjectSignaled(HANDLE object) { - DCHECK(object == user_policy_changed_event_.handle() || - object == machine_policy_changed_event_.handle()) - << "unexpected object signaled policy reload, obj = " - << std::showbase << std::hex << object; - Reload(false); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_loader_win.h b/chrome/browser/policy/policy_loader_win.h deleted file mode 100644 index eb5387c..0000000 --- a/chrome/browser/policy/policy_loader_win.h +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_LOADER_WIN_H_ -#define CHROME_BROWSER_POLICY_POLICY_LOADER_WIN_H_ - -#include <windows.h> -#include <userenv.h> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "base/synchronization/waitable_event.h" -#include "base/values.h" -#include "base/win/object_watcher.h" -#include "components/policy/core/common/async_policy_loader.h" -#include "components/policy/core/common/policy_types.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace policy { - -class AppliedGPOListProvider; -class PolicyLoadStatusSample; -class PolicyMap; -class RegistryDict; - -// Interface for mocking out GPO enumeration in tests. -class AppliedGPOListProvider { - public: - virtual ~AppliedGPOListProvider() {} - virtual DWORD GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) = 0; - virtual BOOL FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) = 0; -}; - -// Loads policies from the Windows registry, and watches for Group Policy -// notifications to trigger reloads. -class PolicyLoaderWin : public AsyncPolicyLoader, - public base::win::ObjectWatcher::Delegate { - public: - // The PReg file name used by GPO. - static const base::FilePath::CharType kPRegFileName[]; - - PolicyLoaderWin(scoped_refptr<base::SequencedTaskRunner> task_runner, - const string16& chrome_policy_key, - AppliedGPOListProvider* gpo_provider); - virtual ~PolicyLoaderWin(); - - // Creates a policy loader that uses the Win API to access GPO. - static scoped_ptr<PolicyLoaderWin> Create( - scoped_refptr<base::SequencedTaskRunner> task_runner, - const string16& chrome_policy_key); - - // AsyncPolicyLoader implementation. - virtual void InitOnBackgroundThread() OVERRIDE; - virtual scoped_ptr<PolicyBundle> Load() OVERRIDE; - - private: - // Builds the Chrome policy schema in |chrome_policy_schema_|. - void BuildChromePolicySchema(); - - // Reads Chrome Policy from a PReg file at the given path and stores the - // result in |policy|. - bool ReadPRegFile(const base::FilePath& preg_file, - RegistryDict* policy, - PolicyLoadStatusSample *status); - - // Loads and parses GPO policy in |policy_object_list| for scope |scope|. If - // successful, stores the result in |policy| and returns true. Returns false - // on failure reading the policy, indicating that policy loading should fall - // back to reading the registry. - bool LoadGPOPolicy(PolicyScope scope, - PGROUP_POLICY_OBJECT policy_object_list, - RegistryDict* policy, - PolicyLoadStatusSample *status); - - // Queries Windows for applied group policy and writes the result to |policy|. - // This is the preferred way to obtain GPO data, there are reports of abuse - // of the registry GPO keys by 3rd-party software. - bool ReadPolicyFromGPO(PolicyScope scope, - RegistryDict* policy, - PolicyLoadStatusSample *status); - - // Parses Chrome policy from |gpo_dict| for the given |scope| and |level| and - // merges it into |chrome_policy_map|. - void LoadChromePolicy(const RegistryDict* gpo_dict, - PolicyLevel level, - PolicyScope scope, - PolicyMap* chrome_policy_map); - - // Loads 3rd-party policy from |gpo_dict| and merges it into |bundle|. - void Load3rdPartyPolicy(const RegistryDict* gpo_dict, - PolicyScope scope, - PolicyBundle* bundle); - - // Installs the watchers for the Group Policy update events. - void SetupWatches(); - - // ObjectWatcher::Delegate overrides: - virtual void OnObjectSignaled(HANDLE object) OVERRIDE; - - bool is_initialized_; - const string16 chrome_policy_key_; - class AppliedGPOListProvider* gpo_provider_; - base::DictionaryValue chrome_policy_schema_; - - base::WaitableEvent user_policy_changed_event_; - base::WaitableEvent machine_policy_changed_event_; - base::win::ObjectWatcher user_policy_watcher_; - base::win::ObjectWatcher machine_policy_watcher_; - bool user_policy_watcher_failed_; - bool machine_policy_watcher_failed_; - - DISALLOW_COPY_AND_ASSIGN(PolicyLoaderWin); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_LOADER_WIN_H_ diff --git a/chrome/browser/policy/policy_loader_win_unittest.cc b/chrome/browser/policy/policy_loader_win_unittest.cc deleted file mode 100644 index 12ee9f6..0000000 --- a/chrome/browser/policy/policy_loader_win_unittest.cc +++ /dev/null @@ -1,1218 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_loader_win.h" - -#include <windows.h> -#include <userenv.h> - -#include <algorithm> -#include <cstring> -#include <functional> -#include <iterator> -#include <vector> - -#include "base/base_paths.h" -#include "base/callback.h" -#include "base/file_util.h" -#include "base/files/file_path.h" -#include "base/files/scoped_temp_dir.h" -#include "base/json/json_writer.h" -#include "base/path_service.h" -#include "base/process/process.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "base/sys_byteorder.h" -#include "base/win/registry.h" -#include "chrome/browser/policy/preg_parser_win.h" -#include "components/json_schema/json_schema_constants.h" -#include "components/policy/core/common/async_policy_provider.h" -#include "components/policy/core/common/configuration_policy_provider_test.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/schema_map.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace schema = json_schema_constants; - -using base::win::RegKey; - -namespace policy { - -namespace { - -// Constants for registry key names. -const wchar_t kPathSep[] = L"\\"; -const wchar_t kThirdParty[] = L"3rdparty"; -const wchar_t kMandatory[] = L"policy"; -const wchar_t kRecommended[] = L"recommended"; -const wchar_t kSchema[] = L"schema"; -const wchar_t kTestPolicyKey[] = L"chrome.policy.key"; - -// Installs |value| in the given registry |path| and |hive|, under the key -// |name|. Returns false on errors. -// Some of the possible Value types are stored after a conversion (e.g. doubles -// are stored as strings), and can only be retrieved if a corresponding schema -// is written. -bool InstallValue(const base::Value& value, - HKEY hive, - const string16& path, - const string16& name) { - // KEY_ALL_ACCESS causes the ctor to create the key if it does not exist yet. - RegKey key(hive, path.c_str(), KEY_ALL_ACCESS); - EXPECT_TRUE(key.Valid()); - switch (value.GetType()) { - case base::Value::TYPE_NULL: - return key.WriteValue(name.c_str(), L"") == ERROR_SUCCESS; - - case base::Value::TYPE_BOOLEAN: { - bool bool_value; - if (!value.GetAsBoolean(&bool_value)) - return false; - return key.WriteValue(name.c_str(), bool_value ? 1 : 0) == ERROR_SUCCESS; - } - - case base::Value::TYPE_INTEGER: { - int int_value; - if (!value.GetAsInteger(&int_value)) - return false; - return key.WriteValue(name.c_str(), int_value) == ERROR_SUCCESS; - } - - case base::Value::TYPE_DOUBLE: { - double double_value; - if (!value.GetAsDouble(&double_value)) - return false; - string16 str_value = UTF8ToUTF16(base::DoubleToString(double_value)); - return key.WriteValue(name.c_str(), str_value.c_str()) == ERROR_SUCCESS; - } - - case base::Value::TYPE_STRING: { - string16 str_value; - if (!value.GetAsString(&str_value)) - return false; - return key.WriteValue(name.c_str(), str_value.c_str()) == ERROR_SUCCESS; - } - - case base::Value::TYPE_DICTIONARY: { - const base::DictionaryValue* sub_dict = NULL; - if (!value.GetAsDictionary(&sub_dict)) - return false; - for (base::DictionaryValue::Iterator it(*sub_dict); - !it.IsAtEnd(); it.Advance()) { - if (!InstallValue(it.value(), hive, path + kPathSep + name, - UTF8ToUTF16(it.key()))) { - return false; - } - } - return true; - } - - case base::Value::TYPE_LIST: { - const base::ListValue* list = NULL; - if (!value.GetAsList(&list)) - return false; - for (size_t i = 0; i < list->GetSize(); ++i) { - const base::Value* item; - if (!list->Get(i, &item)) - return false; - if (!InstallValue(*item, hive, path + kPathSep + name, - base::UintToString16(i + 1))) { - return false; - } - } - return true; - } - - case base::Value::TYPE_BINARY: - return false; - } - NOTREACHED(); - return false; -} - -// Builds a JSON schema that represents the types contained in |value|. -// Ownership is transferred to the caller. -base::DictionaryValue* BuildSchema(const base::Value& value) { - base::DictionaryValue* schema = new base::DictionaryValue(); - switch (value.GetType()) { - case base::Value::TYPE_NULL: - schema->SetString(schema::kType, "null"); - break; - case base::Value::TYPE_BOOLEAN: - schema->SetString(schema::kType, "boolean"); - break; - case base::Value::TYPE_INTEGER: - schema->SetString(schema::kType, "integer"); - break; - case base::Value::TYPE_DOUBLE: - schema->SetString(schema::kType, "number"); - break; - case base::Value::TYPE_STRING: - schema->SetString(schema::kType, "string"); - break; - - case base::Value::TYPE_LIST: { - // Assumes every list element has the same type. - const base::ListValue* list = NULL; - if (value.GetAsList(&list) && !list->empty()) { - schema->SetString(schema::kType, "array"); - schema->Set(schema::kItems, BuildSchema(**list->begin())); - } - break; - } - - case base::Value::TYPE_DICTIONARY: { - const base::DictionaryValue* dict = NULL; - if (value.GetAsDictionary(&dict)) { - base::DictionaryValue* properties = new base::DictionaryValue(); - for (base::DictionaryValue::Iterator it(*dict); - !it.IsAtEnd(); it.Advance()) { - properties->Set(it.key(), BuildSchema(it.value())); - } - schema->SetString(schema::kType, "object"); - schema->Set(schema::kProperties, properties); - } - break; - } - - case base::Value::TYPE_BINARY: - break; - } - return schema; -} - -// Writes a JSON |schema| at the registry entry |name| at |path| -// in the given |hive|. Returns false on failure. -bool WriteSchema(const base::DictionaryValue& schema, - HKEY hive, - const string16& path, - const string16& name) { - std::string encoded; - base::JSONWriter::Write(&schema, &encoded); - if (encoded.empty()) - return false; - string16 encoded16 = UTF8ToUTF16(encoded); - // KEY_ALL_ACCESS causes the ctor to create the key if it does not exist yet. - RegKey key(hive, path.c_str(), KEY_ALL_ACCESS); - EXPECT_TRUE(key.Valid()); - return key.WriteValue(name.c_str(), encoded16.c_str()) == ERROR_SUCCESS; -} - -// Builds a JSON schema for |value| and writes it at the registry entry |name| -// at |path| in the given |hive|. Returns false on failure. -bool InstallSchema(const base::Value& value, - HKEY hive, - const string16& path, - const string16& name) { - scoped_ptr<base::DictionaryValue> schema_dict(BuildSchema(value)); - return WriteSchema(*schema_dict, hive, path, name); -} - -// This class provides sandboxing and mocking for the parts of the Windows -// Registry implementing Group Policy. It prepares two temporary sandbox keys, -// one for HKLM and one for HKCU. A test's calls to the registry are redirected -// by Windows to these sandboxes, allowing the tests to manipulate and access -// policy as if it were active, but without actually changing the parts of the -// Registry that are managed by Group Policy. -class ScopedGroupPolicyRegistrySandbox { - public: - ScopedGroupPolicyRegistrySandbox(); - ~ScopedGroupPolicyRegistrySandbox(); - - private: - void ActivateOverrides(); - void RemoveOverrides(); - - // Deletes the sandbox keys. - void DeleteKeys(); - - std::wstring key_name_; - - // Keys are created for the lifetime of a test to contain - // the sandboxed HKCU and HKLM hives, respectively. - RegKey temp_hkcu_hive_key_; - RegKey temp_hklm_hive_key_; - - DISALLOW_COPY_AND_ASSIGN(ScopedGroupPolicyRegistrySandbox); -}; - -// A test harness that feeds policy via the Chrome GPO registry subtree. -class RegistryTestHarness : public PolicyProviderTestHarness, - public AppliedGPOListProvider { - public: - RegistryTestHarness(HKEY hive, PolicyScope scope); - virtual ~RegistryTestHarness(); - - // PolicyProviderTestHarness: - virtual void SetUp() OVERRIDE; - - virtual ConfigurationPolicyProvider* CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE; - - virtual void InstallEmptyPolicy() OVERRIDE; - virtual void InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) OVERRIDE; - virtual void InstallIntegerPolicy(const std::string& policy_name, - int policy_value) OVERRIDE; - virtual void InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) OVERRIDE; - virtual void InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) OVERRIDE; - virtual void InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) OVERRIDE; - virtual void Install3rdPartyPolicy( - const base::DictionaryValue* policies) OVERRIDE; - - // AppliedGPOListProvider: - virtual DWORD GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) OVERRIDE; - virtual BOOL FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) OVERRIDE; - - // Creates a harness instance that will install policy in HKCU or HKLM, - // respectively. - static PolicyProviderTestHarness* CreateHKCU(); - static PolicyProviderTestHarness* CreateHKLM(); - - private: - HKEY hive_; - - ScopedGroupPolicyRegistrySandbox registry_sandbox_; - - DISALLOW_COPY_AND_ASSIGN(RegistryTestHarness); -}; - -// A test harness that generates PReg files for the provider to read. -class PRegTestHarness : public PolicyProviderTestHarness, - public AppliedGPOListProvider { - public: - PRegTestHarness(); - virtual ~PRegTestHarness(); - - // PolicyProviderTestHarness: - virtual void SetUp() OVERRIDE; - - virtual ConfigurationPolicyProvider* CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) OVERRIDE; - - virtual void InstallEmptyPolicy() OVERRIDE; - virtual void InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) OVERRIDE; - virtual void InstallIntegerPolicy(const std::string& policy_name, - int policy_value) OVERRIDE; - virtual void InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) OVERRIDE; - virtual void InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) OVERRIDE; - virtual void InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) OVERRIDE; - virtual void Install3rdPartyPolicy( - const base::DictionaryValue* policies) OVERRIDE; - - // AppliedGPOListProvider: - virtual DWORD GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) OVERRIDE; - virtual BOOL FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) OVERRIDE; - - // Creates a harness instance. - static PolicyProviderTestHarness* Create(); - - private: - // Helper to append a string16 to an uint8 buffer. - static void AppendChars(std::vector<uint8>* buffer, const string16& chars); - - // Appends a record with the given fields to the PReg file. - void AppendRecordToPRegFile(const string16& path, - const std::string& key, - DWORD type, - DWORD size, - uint8* data); - - // Appends the given DWORD |value| for |path| + |key| to the PReg file. - void AppendDWORDToPRegFile(const string16& path, - const std::string& key, - DWORD value); - - // Appends the given string |value| for |path| + |key| to the PReg file. - void AppendStringToPRegFile(const string16& path, - const std::string& key, - const std::string& value); - - // Appends the given policy |value| for |path| + |key| to the PReg file, - // converting and recursing as necessary. - void AppendPolicyToPRegFile(const string16& path, - const std::string& key, - const base::Value* value); - - base::ScopedTempDir temp_dir_; - base::FilePath preg_file_path_; - GROUP_POLICY_OBJECT gpo_; - - DISALLOW_COPY_AND_ASSIGN(PRegTestHarness); -}; - -ScopedGroupPolicyRegistrySandbox::ScopedGroupPolicyRegistrySandbox() { - // Generate a unique registry key for the override for each test. This - // makes sure that tests executing in parallel won't delete each other's - // key, at DeleteKeys(). - key_name_ = ASCIIToWide(base::StringPrintf( - "SOFTWARE\\chromium unittest %d", - base::Process::Current().pid())); - std::wstring hklm_key_name = key_name_ + L"\\HKLM"; - std::wstring hkcu_key_name = key_name_ + L"\\HKCU"; - - // Create the subkeys to hold the overridden HKLM and HKCU - // policy settings. - temp_hklm_hive_key_.Create(HKEY_CURRENT_USER, - hklm_key_name.c_str(), - KEY_ALL_ACCESS); - temp_hkcu_hive_key_.Create(HKEY_CURRENT_USER, - hkcu_key_name.c_str(), - KEY_ALL_ACCESS); - - ActivateOverrides(); -} - -ScopedGroupPolicyRegistrySandbox::~ScopedGroupPolicyRegistrySandbox() { - RemoveOverrides(); - DeleteKeys(); -} - -void ScopedGroupPolicyRegistrySandbox::ActivateOverrides() { - ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_LOCAL_MACHINE, - temp_hklm_hive_key_.Handle())); - ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_CURRENT_USER, - temp_hkcu_hive_key_.Handle())); -} - -void ScopedGroupPolicyRegistrySandbox::RemoveOverrides() { - ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_LOCAL_MACHINE, 0)); - ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_CURRENT_USER, 0)); -} - -void ScopedGroupPolicyRegistrySandbox::DeleteKeys() { - RegKey key(HKEY_CURRENT_USER, key_name_.c_str(), KEY_ALL_ACCESS); - ASSERT_TRUE(key.Valid()); - key.DeleteKey(L""); -} - -RegistryTestHarness::RegistryTestHarness(HKEY hive, PolicyScope scope) - : PolicyProviderTestHarness(POLICY_LEVEL_MANDATORY, scope), hive_(hive) {} - -RegistryTestHarness::~RegistryTestHarness() {} - -void RegistryTestHarness::SetUp() {} - -ConfigurationPolicyProvider* RegistryTestHarness::CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) { - scoped_ptr<AsyncPolicyLoader> loader( - new PolicyLoaderWin(task_runner, kTestPolicyKey, this)); - return new AsyncPolicyProvider(registry, loader.Pass()); -} - -void RegistryTestHarness::InstallEmptyPolicy() {} - -void RegistryTestHarness::InstallStringPolicy( - const std::string& policy_name, - const std::string& policy_value) { - RegKey key(hive_, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(key.Valid()); - ASSERT_HRESULT_SUCCEEDED(key.WriteValue(UTF8ToUTF16(policy_name).c_str(), - UTF8ToUTF16(policy_value).c_str())); -} - -void RegistryTestHarness::InstallIntegerPolicy( - const std::string& policy_name, - int policy_value) { - RegKey key(hive_, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(key.Valid()); - key.WriteValue(UTF8ToUTF16(policy_name).c_str(), - static_cast<DWORD>(policy_value)); -} - -void RegistryTestHarness::InstallBooleanPolicy( - const std::string& policy_name, - bool policy_value) { - RegKey key(hive_, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(key.Valid()); - key.WriteValue(UTF8ToUTF16(policy_name).c_str(), - static_cast<DWORD>(policy_value)); -} - -void RegistryTestHarness::InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) { - RegKey key(hive_, - (string16(kTestPolicyKey) + ASCIIToUTF16("\\") + - UTF8ToUTF16(policy_name)).c_str(), - KEY_ALL_ACCESS); - ASSERT_TRUE(key.Valid()); - int index = 1; - for (base::ListValue::const_iterator element(policy_value->begin()); - element != policy_value->end(); - ++element) { - std::string element_value; - if (!(*element)->GetAsString(&element_value)) - continue; - std::string name(base::IntToString(index++)); - key.WriteValue(UTF8ToUTF16(name).c_str(), - UTF8ToUTF16(element_value).c_str()); - } -} - -void RegistryTestHarness::InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) { - std::string json; - base::JSONWriter::Write(policy_value, &json); - RegKey key(hive_, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(key.Valid()); - key.WriteValue(UTF8ToUTF16(policy_name).c_str(), - UTF8ToUTF16(json).c_str()); -} - -void RegistryTestHarness::Install3rdPartyPolicy( - const base::DictionaryValue* policies) { - // The first level entries are domains, and the second level entries map - // components to their policy. - const string16 kPathPrefix = string16(kTestPolicyKey) + kPathSep + - kThirdParty + kPathSep; - for (base::DictionaryValue::Iterator domain(*policies); - !domain.IsAtEnd(); domain.Advance()) { - const base::DictionaryValue* components = NULL; - if (!domain.value().GetAsDictionary(&components)) { - ADD_FAILURE(); - continue; - } - for (base::DictionaryValue::Iterator component(*components); - !component.IsAtEnd(); component.Advance()) { - const string16 path = kPathPrefix + - UTF8ToUTF16(domain.key()) + kPathSep + - UTF8ToUTF16(component.key()); - InstallValue(component.value(), hive_, path, kMandatory); - EXPECT_TRUE(InstallSchema(component.value(), hive_, path, kSchema)); - } - } -} - -DWORD RegistryTestHarness::GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) { - *gpo_list = NULL; - return ERROR_ACCESS_DENIED; -} - -BOOL RegistryTestHarness::FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) { - return TRUE; -} - -// static -PolicyProviderTestHarness* RegistryTestHarness::CreateHKCU() { - return new RegistryTestHarness(HKEY_CURRENT_USER, POLICY_SCOPE_USER); -} - -// static -PolicyProviderTestHarness* RegistryTestHarness::CreateHKLM() { - return new RegistryTestHarness(HKEY_LOCAL_MACHINE, POLICY_SCOPE_MACHINE); -} - -PRegTestHarness::PRegTestHarness() - : PolicyProviderTestHarness(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE) {} - -PRegTestHarness::~PRegTestHarness() {} - -void PRegTestHarness::SetUp() { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - preg_file_path_ = temp_dir_.path().Append(PolicyLoaderWin::kPRegFileName); - ASSERT_TRUE(file_util::WriteFile(preg_file_path_, - preg_parser::kPRegFileHeader, - arraysize(preg_parser::kPRegFileHeader))); - - memset(&gpo_, 0, sizeof(GROUP_POLICY_OBJECT)); - gpo_.lpFileSysPath = const_cast<wchar_t*>(temp_dir_.path().value().c_str()); -} - -ConfigurationPolicyProvider* PRegTestHarness::CreateProvider( - SchemaRegistry* registry, - scoped_refptr<base::SequencedTaskRunner> task_runner) { - scoped_ptr<AsyncPolicyLoader> loader( - new PolicyLoaderWin(task_runner, kTestPolicyKey, this)); - return new AsyncPolicyProvider(registry, loader.Pass()); -} - -void PRegTestHarness::InstallEmptyPolicy() {} - -void PRegTestHarness::InstallStringPolicy(const std::string& policy_name, - const std::string& policy_value) { - AppendStringToPRegFile(kTestPolicyKey, policy_name, policy_value); -} - -void PRegTestHarness::InstallIntegerPolicy(const std::string& policy_name, - int policy_value) { - AppendDWORDToPRegFile(kTestPolicyKey, policy_name, policy_value); -} - -void PRegTestHarness::InstallBooleanPolicy(const std::string& policy_name, - bool policy_value) { - AppendDWORDToPRegFile(kTestPolicyKey, policy_name, policy_value); -} - -void PRegTestHarness::InstallStringListPolicy( - const std::string& policy_name, - const base::ListValue* policy_value) { - AppendPolicyToPRegFile(kTestPolicyKey, policy_name, policy_value); -} - -void PRegTestHarness::InstallDictionaryPolicy( - const std::string& policy_name, - const base::DictionaryValue* policy_value) { - std::string json; - base::JSONWriter::Write(policy_value, &json); - AppendStringToPRegFile(kTestPolicyKey, policy_name, json); -} - -void PRegTestHarness::Install3rdPartyPolicy( - const base::DictionaryValue* policies) { - // The first level entries are domains, and the second level entries map - // components to their policy. - const string16 kPathPrefix = string16(kTestPolicyKey) + kPathSep + - kThirdParty + kPathSep; - for (base::DictionaryValue::Iterator domain(*policies); - !domain.IsAtEnd(); domain.Advance()) { - const base::DictionaryValue* components = NULL; - if (!domain.value().GetAsDictionary(&components)) { - ADD_FAILURE(); - continue; - } - const string16 domain_path = kPathPrefix + UTF8ToUTF16(domain.key()); - for (base::DictionaryValue::Iterator component(*components); - !component.IsAtEnd(); component.Advance()) { - const string16 component_path = - domain_path + kPathSep + UTF8ToUTF16(component.key()); - AppendPolicyToPRegFile(component_path, UTF16ToUTF8(kMandatory), - &component.value()); - - scoped_ptr<base::DictionaryValue> schema_dict( - BuildSchema(component.value())); - std::string schema_json; - base::JSONWriter::Write(schema_dict.get(), &schema_json); - if (!schema_json.empty()) { - AppendStringToPRegFile(component_path, UTF16ToUTF8(kSchema), - schema_json); - } - } - } -} - -DWORD PRegTestHarness::GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) { - *gpo_list = flags & GPO_LIST_FLAG_MACHINE ? &gpo_ : NULL; - return ERROR_SUCCESS; -} - -BOOL PRegTestHarness::FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) { - return TRUE; -} - -// static -PolicyProviderTestHarness* PRegTestHarness::Create() { - return new PRegTestHarness(); -} - -// static -void PRegTestHarness::AppendChars(std::vector<uint8>* buffer, - const string16& chars) { - for (string16::const_iterator c(chars.begin()); c != chars.end(); ++c) { - buffer->push_back(*c & 0xff); - buffer->push_back((*c >> 8) & 0xff); - } -} - -void PRegTestHarness::AppendRecordToPRegFile(const string16& path, - const std::string& key, - DWORD type, - DWORD size, - uint8* data) { - std::vector<uint8> buffer; - AppendChars(&buffer, L"["); - AppendChars(&buffer, path); - AppendChars(&buffer, string16(L"\0;", 2)); - AppendChars(&buffer, UTF8ToUTF16(key)); - AppendChars(&buffer, string16(L"\0;", 2)); - type = base::ByteSwapToLE32(type); - uint8* type_data = reinterpret_cast<uint8*>(&type); - buffer.insert(buffer.end(), type_data, type_data + sizeof(DWORD)); - AppendChars(&buffer, L";"); - size = base::ByteSwapToLE32(size); - uint8* size_data = reinterpret_cast<uint8*>(&size); - buffer.insert(buffer.end(), size_data, size_data + sizeof(DWORD)); - AppendChars(&buffer, L";"); - buffer.insert(buffer.end(), data, data + size); - AppendChars(&buffer, L"]"); - - ASSERT_EQ(buffer.size(), - file_util::AppendToFile( - preg_file_path_, - reinterpret_cast<const char*>(vector_as_array(&buffer)), - buffer.size())); -} - -void PRegTestHarness::AppendDWORDToPRegFile(const string16& path, - const std::string& key, - DWORD value) { - value = base::ByteSwapToLE32(value); - AppendRecordToPRegFile(path, key, REG_DWORD, sizeof(DWORD), - reinterpret_cast<uint8*>(&value)); -} - -void PRegTestHarness::AppendStringToPRegFile(const string16& path, - const std::string& key, - const std::string& value) { - string16 string16_value(UTF8ToUTF16(value)); - std::vector<char16> data; - std::transform(string16_value.begin(), string16_value.end(), - std::back_inserter(data), std::ptr_fun(base::ByteSwapToLE16)); - data.push_back(base::ByteSwapToLE16(L'\0')); - - AppendRecordToPRegFile(path, key, REG_SZ, data.size() * sizeof(char16), - reinterpret_cast<uint8*>(vector_as_array(&data))); -} - -void PRegTestHarness::AppendPolicyToPRegFile(const string16& path, - const std::string& key, - const base::Value* value) { - switch (value->GetType()) { - case base::Value::TYPE_BOOLEAN: { - bool boolean_value = false; - ASSERT_TRUE(value->GetAsBoolean(&boolean_value)); - AppendDWORDToPRegFile(path, key, boolean_value); - break; - } - case base::Value::TYPE_INTEGER: { - int int_value = 0; - ASSERT_TRUE(value->GetAsInteger(&int_value)); - AppendDWORDToPRegFile(path, key, int_value); - break; - } - case base::Value::TYPE_DOUBLE: { - double double_value = 0; - ASSERT_TRUE(value->GetAsDouble(&double_value)); - AppendStringToPRegFile(path, key, base::DoubleToString(double_value)); - break; - } - case base::Value::TYPE_STRING: { - std::string string_value; - ASSERT_TRUE(value->GetAsString(&string_value)); - AppendStringToPRegFile(path, key, string_value); - break; - } - case base::Value::TYPE_DICTIONARY: { - string16 subpath = path + kPathSep + UTF8ToUTF16(key); - const base::DictionaryValue* dict = NULL; - ASSERT_TRUE(value->GetAsDictionary(&dict)); - for (base::DictionaryValue::Iterator entry(*dict); !entry.IsAtEnd(); - entry.Advance()) { - AppendPolicyToPRegFile(subpath, entry.key(), &entry.value()); - } - break; - } - case base::Value::TYPE_LIST: { - string16 subpath = path + kPathSep + UTF8ToUTF16(key); - const base::ListValue* list = NULL; - ASSERT_TRUE(value->GetAsList(&list)); - for (size_t i = 0; i < list->GetSize(); ++i) { - const base::Value* entry = NULL; - ASSERT_TRUE(list->Get(i, &entry)); - AppendPolicyToPRegFile(subpath, base::IntToString(i + 1), entry); - } - break; - } - case base::Value::TYPE_BINARY: - case base::Value::TYPE_NULL: { - ADD_FAILURE(); - break; - } - } -} - -} // namespace - -// Instantiate abstract test case for basic policy reading tests. -INSTANTIATE_TEST_CASE_P( - PolicyProviderWinTest, - ConfigurationPolicyProviderTest, - testing::Values(RegistryTestHarness::CreateHKCU, - RegistryTestHarness::CreateHKLM, - PRegTestHarness::Create)); - -// Instantiate abstract test case for 3rd party policy reading tests. -INSTANTIATE_TEST_CASE_P( - ThirdPartyPolicyProviderWinTest, - Configuration3rdPartyPolicyProviderTest, - testing::Values(RegistryTestHarness::CreateHKCU, - RegistryTestHarness::CreateHKLM, - PRegTestHarness::Create)); - -// Test cases for windows policy provider specific functionality. -class PolicyLoaderWinTest : public PolicyTestBase, - public AppliedGPOListProvider { - protected: - // The policy key this tests places data under. This must match the data - // files in chrome/test/data/policy/gpo. - static const char16 kTestPolicyKey[]; - - PolicyLoaderWinTest() - : gpo_list_(NULL), - gpo_list_status_(ERROR_ACCESS_DENIED) {} - virtual ~PolicyLoaderWinTest() {} - - virtual void SetUp() OVERRIDE { - PolicyTestBase::SetUp(); - - ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir_)); - test_data_dir_ = test_data_dir_.AppendASCII("chrome") - .AppendASCII("test") - .AppendASCII("data") - .AppendASCII("policy") - .AppendASCII("gpo"); - - // Unknown components will be filtered out. Register their names with an - // invalid schema to avoid that. - ComponentMap components; - components["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"] = Schema(); - components["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"] = Schema(); - components["int"] = Schema(); - components["merge"] = Schema(); - components["string"] = Schema(); - components["test"] = Schema(); - schema_registry_.RegisterComponents(POLICY_DOMAIN_EXTENSIONS, components); - } - - // AppliedGPOListProvider: - virtual DWORD GetAppliedGPOList(DWORD flags, - LPCTSTR machine_name, - PSID sid_user, - GUID* extension_guid, - PGROUP_POLICY_OBJECT* gpo_list) OVERRIDE { - *gpo_list = gpo_list_; - return gpo_list_status_; - } - virtual BOOL FreeGPOList(PGROUP_POLICY_OBJECT gpo_list) OVERRIDE { - return TRUE; - } - - void InitGPO(GROUP_POLICY_OBJECT* gpo, - DWORD options, - const base::FilePath& path, - GROUP_POLICY_OBJECT* next, - GROUP_POLICY_OBJECT* prev) { - memset(gpo, 0, sizeof(GROUP_POLICY_OBJECT)); - gpo->dwOptions = options; - gpo->lpFileSysPath = const_cast<wchar_t*>(path.value().c_str()); - gpo->pNext = next; - gpo->pPrev = prev; - } - - bool Matches(const PolicyBundle& expected) { - PolicyLoaderWin loader(loop_.message_loop_proxy(), kTestPolicyKey, this); - scoped_ptr<PolicyBundle> loaded( - loader.InitialLoad(schema_registry_.schema_map())); - return loaded->Equals(expected); - } - - void InstallRegistrySentinel() { - RegKey hklm_key(HKEY_CURRENT_USER, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(hklm_key.Valid()); - hklm_key.WriteValue( - UTF8ToUTF16(test_keys::kKeyString).c_str(), - UTF8ToUTF16("registry").c_str()); - } - - bool MatchesRegistrySentinel() { - base::DictionaryValue expected_policy; - expected_policy.SetString(test_keys::kKeyString, "registry"); - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .LoadFrom(&expected_policy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER); - return Matches(expected); - } - - bool MatchesTestBundle() { - base::DictionaryValue expected_policy; - expected_policy.SetBoolean(test_keys::kKeyBoolean, true); - expected_policy.SetString(test_keys::kKeyString, "GPO"); - expected_policy.SetInteger(test_keys::kKeyInteger, 42); - scoped_ptr<base::ListValue> list(new base::ListValue()); - list->AppendString("GPO 1"); - list->AppendString("GPO 2"); - expected_policy.Set(test_keys::kKeyStringList, list.release()); - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .LoadFrom(&expected_policy, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_MACHINE); - return Matches(expected); - } - - ScopedGroupPolicyRegistrySandbox registry_sandbox_; - PGROUP_POLICY_OBJECT gpo_list_; - DWORD gpo_list_status_; - base::FilePath test_data_dir_; -}; - -const char16 PolicyLoaderWinTest::kTestPolicyKey[] = - L"SOFTWARE\\Policies\\Chromium"; - -TEST_F(PolicyLoaderWinTest, HKLMOverHKCU) { - RegKey hklm_key(HKEY_LOCAL_MACHINE, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(hklm_key.Valid()); - hklm_key.WriteValue(UTF8ToUTF16(test_keys::kKeyString).c_str(), - UTF8ToUTF16("hklm").c_str()); - RegKey hkcu_key(HKEY_CURRENT_USER, kTestPolicyKey, KEY_ALL_ACCESS); - ASSERT_TRUE(hkcu_key.Valid()); - hkcu_key.WriteValue(UTF8ToUTF16(test_keys::kKeyString).c_str(), - UTF8ToUTF16("hkcu").c_str()); - - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .Set(test_keys::kKeyString, - POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_MACHINE, - base::Value::CreateStringValue("hklm"), NULL); - EXPECT_TRUE(Matches(expected)); -} - -TEST_F(PolicyLoaderWinTest, Load3rdPartyWithoutSchema) { - base::DictionaryValue dict; - dict.SetString("str", "string value"); - dict.SetInteger("int", 123); - dict.Set("subdict", dict.DeepCopy()); - dict.Set("subsubdict", dict.DeepCopy()); - dict.Set("subsubsubdict", dict.DeepCopy()); - - base::DictionaryValue policy_dict; - policy_dict.Set("extensions.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.policy", - dict.DeepCopy()); - policy_dict.Set("extensions.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.policy", - dict.DeepCopy()); - EXPECT_TRUE(InstallValue(policy_dict, HKEY_LOCAL_MACHINE, - kTestPolicyKey, kThirdParty)); - - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) - .LoadFrom(&dict, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE); - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) - .LoadFrom(&dict, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE); - EXPECT_TRUE(Matches(expected)); -} - -TEST_F(PolicyLoaderWinTest, Merge3rdPartyPolicies) { - // Policy for the same extension will be provided at the 4 level/scope - // combinations, to verify that they overlap as expected. - - const string16 kPathSuffix = - kTestPolicyKey + ASCIIToUTF16("\\3rdparty\\extensions\\merge"); - - const char kUserMandatory[] = "user-mandatory"; - const char kUserRecommended[] = "user-recommended"; - const char kMachineMandatory[] = "machine-mandatory"; - const char kMachineRecommended[] = "machine-recommended"; - - base::DictionaryValue policy; - policy.SetString("a", kMachineMandatory); - EXPECT_TRUE(InstallValue(policy, HKEY_LOCAL_MACHINE, - kPathSuffix, kMandatory)); - policy.SetString("a", kUserMandatory); - policy.SetString("b", kUserMandatory); - EXPECT_TRUE(InstallValue(policy, HKEY_CURRENT_USER, - kPathSuffix, kMandatory)); - policy.SetString("a", kMachineRecommended); - policy.SetString("b", kMachineRecommended); - policy.SetString("c", kMachineRecommended); - EXPECT_TRUE(InstallValue(policy, HKEY_LOCAL_MACHINE, - kPathSuffix, kRecommended)); - policy.SetString("a", kUserRecommended); - policy.SetString("b", kUserRecommended); - policy.SetString("c", kUserRecommended); - policy.SetString("d", kUserRecommended); - EXPECT_TRUE(InstallValue(policy, HKEY_CURRENT_USER, - kPathSuffix, kRecommended)); - - PolicyBundle expected; - PolicyMap& expected_policy = - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "merge")); - expected_policy.Set("a", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, - base::Value::CreateStringValue(kMachineMandatory), NULL); - expected_policy.Set("b", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue(kUserMandatory), NULL); - expected_policy.Set("c", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_MACHINE, - base::Value::CreateStringValue(kMachineRecommended), - NULL); - expected_policy.Set("d", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - base::Value::CreateStringValue(kUserRecommended), NULL); - EXPECT_TRUE(Matches(expected)); -} - -TEST_F(PolicyLoaderWinTest, LoadStringEncodedValues) { - // Create a dictionary with all the types that can be stored encoded in a - // string, to pass to InstallSchema(). Also build an equivalent dictionary - // with the encoded values, to pass to InstallValue(). - base::DictionaryValue policy; - policy.Set("null", base::Value::CreateNullValue()); - policy.SetBoolean("bool", true); - policy.SetInteger("int", -123); - policy.SetDouble("double", 456.78e9); - base::ListValue list; - list.Append(policy.DeepCopy()); - list.Append(policy.DeepCopy()); - policy.Set("list", list.DeepCopy()); - // Encode |policy| before adding the "dict" entry. - std::string encoded_dict; - base::JSONWriter::Write(&policy, &encoded_dict); - ASSERT_FALSE(encoded_dict.empty()); - policy.Set("dict", policy.DeepCopy()); - - std::string encoded_list; - base::JSONWriter::Write(&list, &encoded_list); - ASSERT_FALSE(encoded_list.empty()); - base::DictionaryValue encoded_policy; - encoded_policy.SetString("null", ""); - encoded_policy.SetString("bool", "1"); - encoded_policy.SetString("int", "-123"); - encoded_policy.SetString("double", "456.78e9"); - encoded_policy.SetString("list", encoded_list); - encoded_policy.SetString("dict", encoded_dict); - - const string16 kPathSuffix = - kTestPolicyKey + ASCIIToUTF16("\\3rdparty\\extensions\\string"); - EXPECT_TRUE(InstallSchema(policy, HKEY_CURRENT_USER, kPathSuffix, kSchema)); - EXPECT_TRUE( - InstallValue(encoded_policy, HKEY_CURRENT_USER, kPathSuffix, kMandatory)); - - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "string")) - .LoadFrom(&policy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER); - EXPECT_TRUE(Matches(expected)); -} - -TEST_F(PolicyLoaderWinTest, LoadIntegerEncodedValues) { - base::DictionaryValue policy; - policy.SetBoolean("bool", true); - policy.SetInteger("int", 123); - policy.SetDouble("double", 456.0); - - base::DictionaryValue encoded_policy; - encoded_policy.SetInteger("bool", 1); - encoded_policy.SetInteger("int", 123); - encoded_policy.SetInteger("double", 456); - - const string16 kPathSuffix = - kTestPolicyKey + ASCIIToUTF16("\\3rdparty\\extensions\\int"); - EXPECT_TRUE(InstallSchema(policy, HKEY_CURRENT_USER, kPathSuffix, kSchema)); - EXPECT_TRUE( - InstallValue(encoded_policy, HKEY_CURRENT_USER, kPathSuffix, kMandatory)); - - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "int")) - .LoadFrom(&policy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER); - EXPECT_TRUE(Matches(expected)); -} - -TEST_F(PolicyLoaderWinTest, DefaultPropertySchemaType) { - // Build a schema for an "object" with a default schema for its properties. - base::DictionaryValue default_schema; - default_schema.SetString(schema::kType, "number"); - base::DictionaryValue integer_schema; - integer_schema.SetString(schema::kType, "integer"); - base::DictionaryValue properties; - properties.Set("special-int1", integer_schema.DeepCopy()); - properties.Set("special-int2", integer_schema.DeepCopy()); - base::DictionaryValue schema; - schema.SetString(schema::kType, "object"); - schema.Set(schema::kProperties, properties.DeepCopy()); - schema.Set(schema::kAdditionalProperties, default_schema.DeepCopy()); - - const string16 kPathSuffix = - kTestPolicyKey + ASCIIToUTF16("\\3rdparty\\extensions\\test"); - EXPECT_TRUE(WriteSchema(schema, HKEY_CURRENT_USER, kPathSuffix, kSchema)); - - // Write some test values. - base::DictionaryValue policy; - // These special values have a specific schema for them. - policy.SetInteger("special-int1", 123); - policy.SetString("special-int2", "-456"); - // Other values default to be loaded as doubles. - policy.SetInteger("double1", 789.0); - policy.SetString("double2", "123.456e7"); - policy.SetString("invalid", "omg"); - EXPECT_TRUE(InstallValue(policy, HKEY_CURRENT_USER, kPathSuffix, kMandatory)); - - base::DictionaryValue expected_policy; - expected_policy.SetInteger("special-int1", 123); - expected_policy.SetInteger("special-int2", -456); - expected_policy.SetDouble("double1", 789.0); - expected_policy.SetDouble("double2", 123.456e7); - expected_policy.Set("invalid", base::Value::CreateNullValue()); - PolicyBundle expected; - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "test")) - .LoadFrom(&expected_policy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER); - EXPECT_TRUE(Matches(expected)); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyNotPresent) { - InstallRegistrySentinel(); - gpo_list_ = NULL; - gpo_list_status_ = ERROR_SUCCESS; - - PolicyBundle empty; - EXPECT_TRUE(Matches(empty)); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyEmpty) { - InstallRegistrySentinel(); - base::FilePath gpo_dir(test_data_dir_.AppendASCII("empty")); - GROUP_POLICY_OBJECT gpo; - InitGPO(&gpo, 0, gpo_dir, NULL, NULL); - gpo_list_ = &gpo; - gpo_list_status_ = ERROR_SUCCESS; - - PolicyBundle empty; - EXPECT_TRUE(Matches(empty)); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyNonExistingFile) { - InstallRegistrySentinel(); - GROUP_POLICY_OBJECT gpo; - InitGPO(&gpo, 0, test_data_dir_, NULL, NULL); - gpo_list_ = &gpo; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesRegistrySentinel()); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyBadPath) { - InstallRegistrySentinel(); - base::FilePath gpo_dir(test_data_dir_.AppendASCII("bad")); - GROUP_POLICY_OBJECT gpo; - InitGPO(&gpo, 0, gpo_dir, NULL, NULL); - gpo_list_ = &gpo; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesRegistrySentinel()); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyPresent) { - InstallRegistrySentinel(); - base::FilePath gpo_dir(test_data_dir_.AppendASCII("test1")); - GROUP_POLICY_OBJECT gpo; - InitGPO(&gpo, 0, gpo_dir, NULL, NULL); - gpo_list_ = &gpo; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesTestBundle()); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyMerged) { - InstallRegistrySentinel(); - base::FilePath gpo1_dir(test_data_dir_.AppendASCII("test2")); - base::FilePath gpo2_dir(test_data_dir_.AppendASCII("test1")); - GROUP_POLICY_OBJECT gpo1; - GROUP_POLICY_OBJECT gpo2; - InitGPO(&gpo1, 0, gpo1_dir, &gpo2, NULL); - InitGPO(&gpo2, 0, gpo2_dir, NULL, &gpo1); - gpo_list_ = &gpo1; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesTestBundle()); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyDisabled) { - InstallRegistrySentinel(); - base::FilePath gpo1_dir(test_data_dir_.AppendASCII("test1")); - base::FilePath gpo2_dir(test_data_dir_.AppendASCII("test2")); - GROUP_POLICY_OBJECT gpo1; - GROUP_POLICY_OBJECT gpo2; - InitGPO(&gpo1, 0, gpo1_dir, &gpo2, NULL); - InitGPO(&gpo2, GPO_FLAG_DISABLE, gpo2_dir, NULL, &gpo1); - gpo_list_ = &gpo1; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesTestBundle()); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyForcedPolicy) { - InstallRegistrySentinel(); - base::FilePath gpo1_dir(test_data_dir_.AppendASCII("test1")); - base::FilePath gpo2_dir(test_data_dir_.AppendASCII("test2")); - GROUP_POLICY_OBJECT gpo1; - GROUP_POLICY_OBJECT gpo2; - InitGPO(&gpo1, GPO_FLAG_FORCE, gpo1_dir, &gpo2, NULL); - InitGPO(&gpo2, 0, gpo2_dir, NULL, &gpo1); - gpo_list_ = &gpo1; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesTestBundle()); -} - -TEST_F(PolicyLoaderWinTest, AppliedPolicyUNCPath) { - InstallRegistrySentinel(); - base::FilePath gpo_dir(test_data_dir_.AppendASCII("test1")); - base::FilePath unc_path(L"\\\\some_share\\GPO"); - GROUP_POLICY_OBJECT gpo1; - GROUP_POLICY_OBJECT gpo2; - InitGPO(&gpo1, 0, gpo_dir, &gpo2, NULL); - InitGPO(&gpo2, 0, unc_path, NULL, &gpo1); - gpo_list_ = &gpo1; - gpo_list_status_ = ERROR_SUCCESS; - - EXPECT_TRUE(MatchesRegistrySentinel()); -} - -TEST_F(PolicyLoaderWinTest, LoadExtensionPolicyAlternativeSpelling) { - base::FilePath gpo_dir( - test_data_dir_.AppendASCII("extension_alternative_spelling")); - GROUP_POLICY_OBJECT gpo; - InitGPO(&gpo, 0, gpo_dir, NULL, NULL); - gpo_list_ = &gpo; - gpo_list_status_ = ERROR_SUCCESS; - - PolicyBundle expected; - base::DictionaryValue expected_a; - expected_a.SetInteger("policy 1", 3); - expected_a.SetInteger("policy 2", 3); - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) - .LoadFrom(&expected_a, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE); - base::DictionaryValue expected_b; - expected_b.SetInteger("policy 1", 2); - expected.Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) - .LoadFrom(&expected_b, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE); - EXPECT_TRUE(Matches(expected)); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_service.cc b/chrome/browser/policy/policy_service.cc deleted file mode 100644 index cd07867..0000000 --- a/chrome/browser/policy/policy_service.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_service.h" - -#include "base/values.h" - -namespace policy { - -PolicyChangeRegistrar::PolicyChangeRegistrar(PolicyService* policy_service, - const PolicyNamespace& ns) - : policy_service_(policy_service), - ns_(ns) {} - -PolicyChangeRegistrar::~PolicyChangeRegistrar() { - if (!callback_map_.empty()) - policy_service_->RemoveObserver(ns_.domain, this); -} - -void PolicyChangeRegistrar::Observe(const std::string& policy_name, - const UpdateCallback& callback) { - if (callback_map_.empty()) - policy_service_->AddObserver(ns_.domain, this); - callback_map_[policy_name] = callback; -} - -void PolicyChangeRegistrar::OnPolicyUpdated(const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current) { - if (ns != ns_) - return; - for (CallbackMap::iterator it = callback_map_.begin(); - it != callback_map_.end(); ++it) { - const Value* prev = previous.GetValue(it->first); - const Value* cur = current.GetValue(it->first); - if (!base::Value::Equals(prev, cur)) - it->second.Run(prev, cur); - } -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_service.h b/chrome/browser/policy/policy_service.h deleted file mode 100644 index 259f70a..0000000 --- a/chrome/browser/policy/policy_service.h +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_SERVICE_H_ -#define CHROME_BROWSER_POLICY_POLICY_SERVICE_H_ - -#include <map> -#include <string> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_namespace.h" - -namespace policy { - -// The PolicyService merges policies from all available sources, taking into -// account their priorities. Policy clients can retrieve policy for their domain -// and register for notifications on policy updates. -// -// The PolicyService is available from BrowserProcess as a global singleton. -// There is also a PolicyService for browser-wide policies available from -// BrowserProcess as a global singleton. -class PolicyService { - public: - class Observer { - public: - // Invoked whenever policies for the given |ns| namespace are modified. - // This is only invoked for changes that happen after AddObserver is called. - // |previous| contains the values of the policies before the update, - // and |current| contains the current values. - virtual void OnPolicyUpdated(const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current) = 0; - - // Invoked at most once for each |domain|, when the PolicyService becomes - // ready. If IsInitializationComplete() is false, then this will be invoked - // once all the policy providers have finished loading their policies for - // |domain|. - virtual void OnPolicyServiceInitialized(PolicyDomain domain) {} - - protected: - virtual ~Observer() {} - }; - - virtual ~PolicyService() {} - - // Observes changes to all components of the given |domain|. - virtual void AddObserver(PolicyDomain domain, Observer* observer) = 0; - - virtual void RemoveObserver(PolicyDomain domain, Observer* observer) = 0; - - virtual const PolicyMap& GetPolicies(const PolicyNamespace& ns) const = 0; - - // The PolicyService loads policy from several sources, and some require - // asynchronous loads. IsInitializationComplete() returns true once all - // sources have loaded their policies for the given |domain|. - // It is safe to read policy from the PolicyService even if - // IsInitializationComplete() is false; there will be an OnPolicyUpdated() - // notification once new policies become available. - // - // OnPolicyServiceInitialized() is called when IsInitializationComplete() - // becomes true, which happens at most once for each domain. - // If IsInitializationComplete() is already true for |domain| when an Observer - // is registered, then that Observer will not receive an - // OnPolicyServiceInitialized() notification. - virtual bool IsInitializationComplete(PolicyDomain domain) const = 0; - - // Asks the PolicyService to reload policy from all available policy sources. - // |callback| is invoked once every source has reloaded its policies, and - // GetPolicies() is guaranteed to return the updated values at that point. - virtual void RefreshPolicies(const base::Closure& callback) = 0; -}; - -// A registrar that only observes changes to particular policies within the -// PolicyMap for the given policy namespace. -class PolicyChangeRegistrar : public PolicyService::Observer { - public: - typedef base::Callback<void(const Value*, const Value*)> UpdateCallback; - - // Observes updates to the given (domain, component_id) namespace in the given - // |policy_service|, and notifies |observer| whenever any of the registered - // policy keys changes. Both the |policy_service| and the |observer| must - // outlive |this|. - PolicyChangeRegistrar(PolicyService* policy_service, - const PolicyNamespace& ns); - - virtual ~PolicyChangeRegistrar(); - - // Will invoke |callback| whenever |policy_name| changes its value, as long - // as this registrar exists. - // Only one callback can be registed per policy name; a second call with the - // same |policy_name| will overwrite the previous callback. - void Observe(const std::string& policy_name, const UpdateCallback& callback); - - // Implementation of PolicyService::Observer: - virtual void OnPolicyUpdated(const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current) OVERRIDE; - - private: - typedef std::map<std::string, UpdateCallback> CallbackMap; - - PolicyService* policy_service_; - PolicyNamespace ns_; - CallbackMap callback_map_; - - DISALLOW_COPY_AND_ASSIGN(PolicyChangeRegistrar); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_SERVICE_H_ diff --git a/chrome/browser/policy/policy_service_impl.cc b/chrome/browser/policy/policy_service_impl.cc deleted file mode 100644 index 6515cf9..0000000 --- a/chrome/browser/policy/policy_service_impl.cc +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_service_impl.h" - -#include <algorithm> - -#include "base/bind.h" -#include "base/message_loop/message_loop.h" -#include "base/stl_util.h" -#include "components/policy/core/common/policy_bundle.h" -#include "components/policy/core/common/policy_map.h" - -namespace policy { - -typedef PolicyServiceImpl::Providers::const_iterator Iterator; - -PolicyServiceImpl::PolicyServiceImpl( - const Providers& providers, - const PreprocessCallback& preprocess_callback) - : preprocess_callback_(preprocess_callback), - update_task_ptr_factory_(this) { - for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) - initialization_complete_[domain] = true; - providers_ = providers; - for (Iterator it = providers.begin(); it != providers.end(); ++it) { - ConfigurationPolicyProvider* provider = *it; - provider->AddObserver(this); - for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) { - initialization_complete_[domain] &= - provider->IsInitializationComplete(static_cast<PolicyDomain>(domain)); - } - } - // There are no observers yet, but calls to GetPolicies() should already get - // the processed policy values. - MergeAndTriggerUpdates(); -} - -PolicyServiceImpl::~PolicyServiceImpl() { - for (Iterator it = providers_.begin(); it != providers_.end(); ++it) - (*it)->RemoveObserver(this); - STLDeleteValues(&observers_); -} - -void PolicyServiceImpl::AddObserver(PolicyDomain domain, - PolicyService::Observer* observer) { - Observers*& list = observers_[domain]; - if (!list) - list = new Observers(); - list->AddObserver(observer); -} - -void PolicyServiceImpl::RemoveObserver(PolicyDomain domain, - PolicyService::Observer* observer) { - ObserverMap::iterator it = observers_.find(domain); - if (it == observers_.end()) { - NOTREACHED(); - return; - } - it->second->RemoveObserver(observer); - if (!it->second->might_have_observers()) { - delete it->second; - observers_.erase(it); - } -} - -const PolicyMap& PolicyServiceImpl::GetPolicies( - const PolicyNamespace& ns) const { - return policy_bundle_.Get(ns); -} - -bool PolicyServiceImpl::IsInitializationComplete(PolicyDomain domain) const { - DCHECK(domain >= 0 && domain < POLICY_DOMAIN_SIZE); - return initialization_complete_[domain]; -} - -void PolicyServiceImpl::RefreshPolicies(const base::Closure& callback) { - if (!callback.is_null()) - refresh_callbacks_.push_back(callback); - - if (providers_.empty()) { - // Refresh is immediately complete if there are no providers. See the note - // on OnUpdatePolicy() about why this is a posted task. - update_task_ptr_factory_.InvalidateWeakPtrs(); - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&PolicyServiceImpl::MergeAndTriggerUpdates, - update_task_ptr_factory_.GetWeakPtr())); - } else { - // Some providers might invoke OnUpdatePolicy synchronously while handling - // RefreshPolicies. Mark all as pending before refreshing. - for (Iterator it = providers_.begin(); it != providers_.end(); ++it) - refresh_pending_.insert(*it); - for (Iterator it = providers_.begin(); it != providers_.end(); ++it) - (*it)->RefreshPolicies(); - } -} - -void PolicyServiceImpl::OnUpdatePolicy(ConfigurationPolicyProvider* provider) { - DCHECK_EQ(1, std::count(providers_.begin(), providers_.end(), provider)); - refresh_pending_.erase(provider); - - // Note: a policy change may trigger further policy changes in some providers. - // For example, disabling SigninAllowed would cause the CloudPolicyManager to - // drop all its policies, which makes this method enter again for that - // provider. - // - // Therefore this update is posted asynchronously, to prevent reentrancy in - // MergeAndTriggerUpdates. Also, cancel a pending update if there is any, - // since both will produce the same PolicyBundle. - update_task_ptr_factory_.InvalidateWeakPtrs(); - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&PolicyServiceImpl::MergeAndTriggerUpdates, - update_task_ptr_factory_.GetWeakPtr())); -} - -void PolicyServiceImpl::NotifyNamespaceUpdated( - const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current) { - ObserverMap::iterator iterator = observers_.find(ns.domain); - if (iterator != observers_.end()) { - FOR_EACH_OBSERVER(PolicyService::Observer, - *iterator->second, - OnPolicyUpdated(ns, previous, current)); - } -} - -void PolicyServiceImpl::MergeAndTriggerUpdates() { - // Merge from each provider in their order of priority. - PolicyBundle bundle; - for (Iterator it = providers_.begin(); it != providers_.end(); ++it) { - PolicyBundle provided_bundle; - provided_bundle.CopyFrom((*it)->policies()); - if (!preprocess_callback_.is_null()) - preprocess_callback_.Run(&provided_bundle); - bundle.MergeFrom(provided_bundle); - } - - // Swap first, so that observers that call GetPolicies() see the current - // values. - policy_bundle_.Swap(&bundle); - - // Only notify observers of namespaces that have been modified. - const PolicyMap kEmpty; - PolicyBundle::const_iterator it_new = policy_bundle_.begin(); - PolicyBundle::const_iterator end_new = policy_bundle_.end(); - PolicyBundle::const_iterator it_old = bundle.begin(); - PolicyBundle::const_iterator end_old = bundle.end(); - while (it_new != end_new && it_old != end_old) { - if (it_new->first < it_old->first) { - // A new namespace is available. - NotifyNamespaceUpdated(it_new->first, kEmpty, *it_new->second); - ++it_new; - } else if (it_old->first < it_new->first) { - // A previously available namespace is now gone. - NotifyNamespaceUpdated(it_old->first, *it_old->second, kEmpty); - ++it_old; - } else { - if (!it_new->second->Equals(*it_old->second)) { - // An existing namespace's policies have changed. - NotifyNamespaceUpdated(it_new->first, *it_old->second, *it_new->second); - } - ++it_new; - ++it_old; - } - } - - // Send updates for the remaining new namespaces, if any. - for (; it_new != end_new; ++it_new) - NotifyNamespaceUpdated(it_new->first, kEmpty, *it_new->second); - - // Sends updates for the remaining removed namespaces, if any. - for (; it_old != end_old; ++it_old) - NotifyNamespaceUpdated(it_old->first, *it_old->second, kEmpty); - - CheckInitializationComplete(); - CheckRefreshComplete(); -} - -void PolicyServiceImpl::CheckInitializationComplete() { - // Check if all the providers just became initialized for each domain; if so, - // notify that domain's observers. - for (int domain = 0; domain < POLICY_DOMAIN_SIZE; ++domain) { - if (initialization_complete_[domain]) - continue; - - PolicyDomain policy_domain = static_cast<PolicyDomain>(domain); - - bool all_complete = true; - for (Iterator it = providers_.begin(); it != providers_.end(); ++it) { - if (!(*it)->IsInitializationComplete(policy_domain)) { - all_complete = false; - break; - } - } - if (all_complete) { - initialization_complete_[domain] = true; - ObserverMap::iterator iter = observers_.find(policy_domain); - if (iter != observers_.end()) { - FOR_EACH_OBSERVER(PolicyService::Observer, - *iter->second, - OnPolicyServiceInitialized(policy_domain)); - } - } - } -} - -void PolicyServiceImpl::CheckRefreshComplete() { - // Invoke all the callbacks if a refresh has just fully completed. - if (refresh_pending_.empty() && !refresh_callbacks_.empty()) { - std::vector<base::Closure> callbacks; - callbacks.swap(refresh_callbacks_); - std::vector<base::Closure>::iterator it; - for (it = callbacks.begin(); it != callbacks.end(); ++it) - it->Run(); - } -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_service_impl.h b/chrome/browser/policy/policy_service_impl.h deleted file mode 100644 index 1628df5..0000000 --- a/chrome/browser/policy/policy_service_impl.h +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_SERVICE_IMPL_H_ -#define CHROME_BROWSER_POLICY_POLICY_SERVICE_IMPL_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "chrome/browser/policy/policy_service.h" -#include "components/policy/core/common/configuration_policy_provider.h" -#include "components/policy/core/common/policy_bundle.h" - -namespace policy { - -class PolicyMap; - -class PolicyServiceImpl : public PolicyService, - public ConfigurationPolicyProvider::Observer { - public: - typedef std::vector<ConfigurationPolicyProvider*> Providers; - typedef base::Callback<void(PolicyBundle*)> PreprocessCallback; - - // The PolicyServiceImpl will merge policies from |providers|. |providers| - // must be sorted in decreasing order of priority; the first provider will - // have the highest priority. The PolicyServiceImpl does not take ownership of - // the providers, and they must outlive the PolicyServiceImpl. - // |preprocess_callback| will be applied every PolicyBundle before merginng. - PolicyServiceImpl(const Providers& providers, - const PreprocessCallback& preprocess_callback); - - virtual ~PolicyServiceImpl(); - - // PolicyService overrides: - virtual void AddObserver(PolicyDomain domain, - PolicyService::Observer* observer) OVERRIDE; - virtual void RemoveObserver(PolicyDomain domain, - PolicyService::Observer* observer) OVERRIDE; - virtual const PolicyMap& GetPolicies( - const PolicyNamespace& ns) const OVERRIDE; - virtual bool IsInitializationComplete(PolicyDomain domain) const OVERRIDE; - virtual void RefreshPolicies(const base::Closure& callback) OVERRIDE; - - private: - typedef ObserverList<PolicyService::Observer, true> Observers; - typedef std::map<PolicyDomain, Observers*> ObserverMap; - - // ConfigurationPolicyProvider::Observer overrides: - virtual void OnUpdatePolicy(ConfigurationPolicyProvider* provider) OVERRIDE; - - // Posts a task to notify observers of |ns| that its policies have changed, - // passing along the |previous| and the |current| policies. - void NotifyNamespaceUpdated(const PolicyNamespace& ns, - const PolicyMap& previous, - const PolicyMap& current); - - // Combines the policies from all the providers, and notifies the observers - // of namespaces whose policies have been modified. - void MergeAndTriggerUpdates(); - - // Checks if all providers are initialized, and notifies the observers - // if the service just became initialized. - void CheckInitializationComplete(); - - // Invokes all the refresh callbacks if there are no more refreshes pending. - void CheckRefreshComplete(); - - // The providers passed in the constructor, in order of decreasing priority. - Providers providers_; - - // Maps each policy namespace to its current policies. - PolicyBundle policy_bundle_; - - // Maps each policy domain to its observer list. - ObserverMap observers_; - - // True if all the providers are initialized for the indexed policy domain. - bool initialization_complete_[POLICY_DOMAIN_SIZE]; - - // Set of providers that have a pending update that was triggered by a - // call to RefreshPolicies(). - std::set<ConfigurationPolicyProvider*> refresh_pending_; - - // Callback invoked to manipulate a PolicyBundle before it is merged. - PreprocessCallback preprocess_callback_; - - // List of callbacks to invoke once all providers refresh after a - // RefreshPolicies() call. - std::vector<base::Closure> refresh_callbacks_; - - // Used to create tasks to delay new policy updates while we may be already - // processing previous policy updates. - base::WeakPtrFactory<PolicyServiceImpl> update_task_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(PolicyServiceImpl); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_SERVICE_IMPL_H_ diff --git a/chrome/browser/policy/policy_service_impl_unittest.cc b/chrome/browser/policy/policy_service_impl_unittest.cc deleted file mode 100644 index 8bf2b8b..0000000 --- a/chrome/browser/policy/policy_service_impl_unittest.cc +++ /dev/null @@ -1,651 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_service_impl.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "base/run_loop.h" -#include "base/values.h" -#include "chrome/browser/policy/mock_policy_service.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/mock_configuration_policy_provider.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::AnyNumber; -using ::testing::Mock; -using ::testing::Return; -using ::testing::_; - -namespace policy { - -namespace { - -const char kExtension[] = "extension-id"; -const char kSameLevelPolicy[] = "policy-same-level-and-scope"; -const char kDiffLevelPolicy[] = "chrome-diff-level-and-scope"; - -void SetPolicyMapValue(const std::string& key, - const std::string& value, - PolicyBundle* bundle) { - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .Set(key, - POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, - new base::StringValue(value), - NULL); -} - -// Helper to compare the arguments to an EXPECT_CALL of OnPolicyUpdated() with -// their expected values. -MATCHER_P(PolicyEquals, expected, "") { - return arg.Equals(*expected); -} - -// Helper to compare the arguments to an EXPECT_CALL of OnPolicyValueUpdated() -// with their expected values. -MATCHER_P(ValueEquals, expected, "") { - return base::Value::Equals(arg, expected); -} - -// Helper that fills |bundle| with test policies. -void AddTestPolicies(PolicyBundle* bundle, - const char* value, - PolicyLevel level, - PolicyScope scope) { - PolicyMap* policy_map = - &bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - policy_map->Set(kSameLevelPolicy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue(value), NULL); - policy_map->Set(kDiffLevelPolicy, level, scope, - base::Value::CreateStringValue(value), NULL); - policy_map = - &bundle->Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension)); - policy_map->Set(kSameLevelPolicy, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, base::Value::CreateStringValue(value), - NULL); - policy_map->Set(kDiffLevelPolicy, level, scope, - base::Value::CreateStringValue(value), NULL); -} - -// Observer class that changes the policy in the passed provider when the -// callback is invoked. -class ChangePolicyObserver : public PolicyService::Observer { - public: - explicit ChangePolicyObserver(MockConfigurationPolicyProvider* provider) - : provider_(provider), - observer_invoked_(false) {} - - virtual void OnPolicyUpdated(const PolicyNamespace&, - const PolicyMap& previous, - const PolicyMap& current) OVERRIDE { - PolicyMap new_policy; - new_policy.Set("foo", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(14), NULL); - provider_->UpdateChromePolicy(new_policy); - observer_invoked_ = true; - } - - bool observer_invoked() const { return observer_invoked_; } - - private: - MockConfigurationPolicyProvider* provider_; - bool observer_invoked_; -}; - -} // namespace - -class PolicyServiceTest : public testing::Test { - public: - PolicyServiceTest() {} - virtual void SetUp() OVERRIDE { - EXPECT_CALL(provider0_, IsInitializationComplete(_)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(provider1_, IsInitializationComplete(_)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(provider2_, IsInitializationComplete(_)) - .WillRepeatedly(Return(true)); - - provider0_.Init(); - provider1_.Init(); - provider2_.Init(); - - policy0_.Set("pre", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(13), NULL); - provider0_.UpdateChromePolicy(policy0_); - - PolicyServiceImpl::Providers providers; - providers.push_back(&provider0_); - providers.push_back(&provider1_); - providers.push_back(&provider2_); - policy_service_.reset(new PolicyServiceImpl( - providers, PolicyServiceImpl::PreprocessCallback())); - } - - virtual void TearDown() OVERRIDE { - provider0_.Shutdown(); - provider1_.Shutdown(); - provider2_.Shutdown(); - } - - MOCK_METHOD2(OnPolicyValueUpdated, void(const base::Value*, - const base::Value*)); - - MOCK_METHOD0(OnPolicyRefresh, void()); - - // Returns true if the policies for namespace |ns| match |expected|. - bool VerifyPolicies(const PolicyNamespace& ns, - const PolicyMap& expected) { - return policy_service_->GetPolicies(ns).Equals(expected); - } - - void RunUntilIdle() { - base::RunLoop loop; - loop.RunUntilIdle(); - } - - protected: - base::MessageLoop loop_; - MockConfigurationPolicyProvider provider0_; - MockConfigurationPolicyProvider provider1_; - MockConfigurationPolicyProvider provider2_; - PolicyMap policy0_; - PolicyMap policy1_; - PolicyMap policy2_; - scoped_ptr<PolicyServiceImpl> policy_service_; - - private: - DISALLOW_COPY_AND_ASSIGN(PolicyServiceTest); -}; - -TEST_F(PolicyServiceTest, LoadsPoliciesBeforeProvidersRefresh) { - PolicyMap expected; - expected.Set("pre", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(13), NULL); - EXPECT_TRUE(VerifyPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), expected)); -} - -TEST_F(PolicyServiceTest, NotifyObservers) { - MockPolicyServiceObserver observer; - policy_service_->AddObserver(POLICY_DOMAIN_CHROME, &observer); - - PolicyMap expectedPrevious; - expectedPrevious.Set("pre", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(13), NULL); - - PolicyMap expectedCurrent; - expectedCurrent.CopyFrom(expectedPrevious); - expectedCurrent.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(123), NULL); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(123), NULL); - EXPECT_CALL(observer, OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_CHROME, - std::string()), - PolicyEquals(&expectedPrevious), - PolicyEquals(&expectedCurrent))); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(&observer); - - // No changes. - EXPECT_CALL(observer, OnPolicyUpdated(_, _, _)).Times(0); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_TRUE(VerifyPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), expectedCurrent)); - - // New policy. - expectedPrevious.CopyFrom(expectedCurrent); - expectedCurrent.Set("bbb", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(456), NULL); - policy0_.Set("bbb", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(456), NULL); - EXPECT_CALL(observer, OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_CHROME, - std::string()), - PolicyEquals(&expectedPrevious), - PolicyEquals(&expectedCurrent))); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(&observer); - - // Removed policy. - expectedPrevious.CopyFrom(expectedCurrent); - expectedCurrent.Erase("bbb"); - policy0_.Erase("bbb"); - EXPECT_CALL(observer, OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_CHROME, - std::string()), - PolicyEquals(&expectedPrevious), - PolicyEquals(&expectedCurrent))); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(&observer); - - // Changed policy. - expectedPrevious.CopyFrom(expectedCurrent); - expectedCurrent.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(789), NULL); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(789), NULL); - - EXPECT_CALL(observer, OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_CHROME, - std::string()), - PolicyEquals(&expectedPrevious), - PolicyEquals(&expectedCurrent))); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(&observer); - - // No changes again. - EXPECT_CALL(observer, OnPolicyUpdated(_, _, _)).Times(0); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_TRUE(VerifyPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), expectedCurrent)); - - policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, &observer); -} - -TEST_F(PolicyServiceTest, NotifyObserversInMultipleNamespaces) { - const std::string kExtension0("extension-0"); - const std::string kExtension1("extension-1"); - const std::string kExtension2("extension-2"); - MockPolicyServiceObserver chrome_observer; - MockPolicyServiceObserver extension_observer; - policy_service_->AddObserver(POLICY_DOMAIN_CHROME, &chrome_observer); - policy_service_->AddObserver(POLICY_DOMAIN_EXTENSIONS, &extension_observer); - - PolicyMap previous_policy_map; - previous_policy_map.Set("pre", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(13), NULL); - PolicyMap policy_map; - policy_map.CopyFrom(previous_policy_map); - policy_map.Set("policy", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("value"), NULL); - - scoped_ptr<PolicyBundle> bundle(new PolicyBundle()); - // The initial setup includes a policy for chrome that is now changing. - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .CopyFrom(policy_map); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension0)) - .CopyFrom(policy_map); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension1)) - .CopyFrom(policy_map); - - const PolicyMap kEmptyPolicyMap; - EXPECT_CALL( - chrome_observer, - OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), - PolicyEquals(&previous_policy_map), - PolicyEquals(&policy_map))); - EXPECT_CALL( - extension_observer, - OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension0), - PolicyEquals(&kEmptyPolicyMap), - PolicyEquals(&policy_map))); - EXPECT_CALL( - extension_observer, - OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension1), - PolicyEquals(&kEmptyPolicyMap), - PolicyEquals(&policy_map))); - provider0_.UpdatePolicy(bundle.Pass()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&chrome_observer); - Mock::VerifyAndClearExpectations(&extension_observer); - - // Chrome policy stays the same, kExtension0 is gone, kExtension1 changes, - // and kExtension2 is new. - previous_policy_map.CopyFrom(policy_map); - bundle.reset(new PolicyBundle()); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .CopyFrom(policy_map); - policy_map.Set("policy", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("another value"), NULL); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension1)) - .CopyFrom(policy_map); - bundle->Get(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension2)) - .CopyFrom(policy_map); - - EXPECT_CALL(chrome_observer, OnPolicyUpdated(_, _, _)).Times(0); - EXPECT_CALL( - extension_observer, - OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension0), - PolicyEquals(&previous_policy_map), - PolicyEquals(&kEmptyPolicyMap))); - EXPECT_CALL( - extension_observer, - OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension1), - PolicyEquals(&previous_policy_map), - PolicyEquals(&policy_map))); - EXPECT_CALL( - extension_observer, - OnPolicyUpdated(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension2), - PolicyEquals(&kEmptyPolicyMap), - PolicyEquals(&policy_map))); - provider0_.UpdatePolicy(bundle.Pass()); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(&chrome_observer); - Mock::VerifyAndClearExpectations(&extension_observer); - - policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, &chrome_observer); - policy_service_->RemoveObserver(POLICY_DOMAIN_EXTENSIONS, - &extension_observer); -} - -TEST_F(PolicyServiceTest, ObserverChangesPolicy) { - ChangePolicyObserver observer(&provider0_); - policy_service_->AddObserver(POLICY_DOMAIN_CHROME, &observer); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(123), NULL); - policy0_.Set("bbb", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(1234), NULL); - // Should not crash. - provider0_.UpdateChromePolicy(policy0_); - policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, &observer); - EXPECT_TRUE(observer.observer_invoked()); -} - -TEST_F(PolicyServiceTest, Priorities) { - PolicyMap expected; - expected.Set("pre", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(13), NULL); - expected.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(0), NULL); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(0), NULL); - policy1_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(1), NULL); - policy2_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(2), NULL); - provider0_.UpdateChromePolicy(policy0_); - provider1_.UpdateChromePolicy(policy1_); - provider2_.UpdateChromePolicy(policy2_); - EXPECT_TRUE(VerifyPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), expected)); - - expected.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(1), NULL); - policy0_.Erase("aaa"); - provider0_.UpdateChromePolicy(policy0_); - EXPECT_TRUE(VerifyPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), expected)); - - expected.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(2), NULL); - policy1_.Set("aaa", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - base::Value::CreateIntegerValue(1), NULL); - provider1_.UpdateChromePolicy(policy1_); - EXPECT_TRUE(VerifyPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()), expected)); -} - -TEST_F(PolicyServiceTest, PolicyChangeRegistrar) { - scoped_ptr<PolicyChangeRegistrar> registrar(new PolicyChangeRegistrar( - policy_service_.get(), - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))); - - // Starting to observe existing policies doesn't trigger a notification. - EXPECT_CALL(*this, OnPolicyValueUpdated(_, _)).Times(0); - registrar->Observe("pre", base::Bind( - &PolicyServiceTest::OnPolicyValueUpdated, - base::Unretained(this))); - registrar->Observe("aaa", base::Bind( - &PolicyServiceTest::OnPolicyValueUpdated, - base::Unretained(this))); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(this); - - // Changing it now triggers a notification. - base::FundamentalValue kValue0(0); - EXPECT_CALL(*this, OnPolicyValueUpdated(NULL, ValueEquals(&kValue0))); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue0.DeepCopy(), NULL); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(this); - - // Changing other values doesn't trigger a notification. - EXPECT_CALL(*this, OnPolicyValueUpdated(_, _)).Times(0); - policy0_.Set("bbb", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue0.DeepCopy(), NULL); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(this); - - // Modifying the value triggers a notification. - base::FundamentalValue kValue1(1); - EXPECT_CALL(*this, OnPolicyValueUpdated(ValueEquals(&kValue0), - ValueEquals(&kValue1))); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue1.DeepCopy(), NULL); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(this); - - // Removing the value triggers a notification. - EXPECT_CALL(*this, OnPolicyValueUpdated(ValueEquals(&kValue1), NULL)); - policy0_.Erase("aaa"); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(this); - - // No more notifications after destroying the registrar. - EXPECT_CALL(*this, OnPolicyValueUpdated(_, _)).Times(0); - registrar.reset(); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue1.DeepCopy(), NULL); - policy0_.Set("pre", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue1.DeepCopy(), NULL); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(this); -} - -TEST_F(PolicyServiceTest, RefreshPolicies) { - EXPECT_CALL(provider0_, RefreshPolicies()).Times(AnyNumber()); - EXPECT_CALL(provider1_, RefreshPolicies()).Times(AnyNumber()); - EXPECT_CALL(provider2_, RefreshPolicies()).Times(AnyNumber()); - - EXPECT_CALL(*this, OnPolicyRefresh()).Times(0); - policy_service_->RefreshPolicies(base::Bind( - &PolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - // Let any queued observer tasks run. - RunUntilIdle(); - Mock::VerifyAndClearExpectations(this); - - EXPECT_CALL(*this, OnPolicyRefresh()).Times(0); - base::FundamentalValue kValue0(0); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue0.DeepCopy(), NULL); - provider0_.UpdateChromePolicy(policy0_); - Mock::VerifyAndClearExpectations(this); - - EXPECT_CALL(*this, OnPolicyRefresh()).Times(0); - base::FundamentalValue kValue1(1); - policy1_.Set("aaa", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - kValue1.DeepCopy(), NULL); - provider1_.UpdateChromePolicy(policy1_); - Mock::VerifyAndClearExpectations(this); - - // A provider can refresh more than once after a RefreshPolicies call, but - // OnPolicyRefresh should be triggered only after all providers are - // refreshed. - EXPECT_CALL(*this, OnPolicyRefresh()).Times(0); - policy1_.Set("bbb", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, - kValue1.DeepCopy(), NULL); - provider1_.UpdateChromePolicy(policy1_); - Mock::VerifyAndClearExpectations(this); - - // If another RefreshPolicies() call happens while waiting for a previous - // one to complete, then all providers must refresh again. - EXPECT_CALL(*this, OnPolicyRefresh()).Times(0); - policy_service_->RefreshPolicies(base::Bind( - &PolicyServiceTest::OnPolicyRefresh, - base::Unretained(this))); - RunUntilIdle(); - Mock::VerifyAndClearExpectations(this); - - EXPECT_CALL(*this, OnPolicyRefresh()).Times(0); - policy2_.Set("bbb", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue0.DeepCopy(), NULL); - provider2_.UpdateChromePolicy(policy2_); - Mock::VerifyAndClearExpectations(this); - - // Providers 0 and 1 must reload again. - EXPECT_CALL(*this, OnPolicyRefresh()).Times(2); - base::FundamentalValue kValue2(2); - policy0_.Set("aaa", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - kValue2.DeepCopy(), NULL); - provider0_.UpdateChromePolicy(policy0_); - provider1_.UpdateChromePolicy(policy1_); - Mock::VerifyAndClearExpectations(this); - - const PolicyMap& policies = policy_service_->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - EXPECT_TRUE(base::Value::Equals(&kValue2, policies.GetValue("aaa"))); - EXPECT_TRUE(base::Value::Equals(&kValue0, policies.GetValue("bbb"))); -} - -TEST_F(PolicyServiceTest, NamespaceMerge) { - scoped_ptr<PolicyBundle> bundle0(new PolicyBundle()); - scoped_ptr<PolicyBundle> bundle1(new PolicyBundle()); - scoped_ptr<PolicyBundle> bundle2(new PolicyBundle()); - - AddTestPolicies(bundle0.get(), "bundle0", - POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER); - AddTestPolicies(bundle1.get(), "bundle1", - POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER); - AddTestPolicies(bundle2.get(), "bundle2", - POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE); - - provider0_.UpdatePolicy(bundle0.Pass()); - provider1_.UpdatePolicy(bundle1.Pass()); - provider2_.UpdatePolicy(bundle2.Pass()); - RunUntilIdle(); - - PolicyMap expected; - // For policies of the same level and scope, the first provider takes - // precedence, on every namespace. - expected.Set(kSameLevelPolicy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateStringValue("bundle0"), NULL); - // For policies with different levels and scopes, the highest priority - // level/scope combination takes precedence, on every namespace. - expected.Set(kDiffLevelPolicy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, - base::Value::CreateStringValue("bundle2"), NULL); - EXPECT_TRUE(policy_service_->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())).Equals(expected)); - EXPECT_TRUE(policy_service_->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, kExtension)).Equals(expected)); -} - -TEST_F(PolicyServiceTest, PolicyPreprocessing) { - // Reset the PolicyServiceImpl to one that has the preprocessor. - PolicyServiceImpl::Providers providers; - providers.push_back(&provider0_); - policy_service_.reset(new PolicyServiceImpl( - providers, base::Bind(&SetPolicyMapValue, kSameLevelPolicy, "bar"))); - - // Set the policy value to "foo". - scoped_ptr<PolicyBundle> bundle(new PolicyBundle()); - PolicyMap& map = - bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - map.Set(kSameLevelPolicy, - POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, - base::Value::CreateStringValue("foo"), - NULL); - - // Push the update through the provider. - provider0_.UpdatePolicy(bundle.Pass()); - RunUntilIdle(); - - // The value should have been changed from "foo" to "bar". - const PolicyMap& actual = policy_service_->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - PolicyMap expected; - expected.Set(kSameLevelPolicy, - POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, - base::Value::CreateStringValue("bar"), - NULL); - EXPECT_TRUE(actual.Equals(expected)); -} - -TEST_F(PolicyServiceTest, IsInitializationComplete) { - // |provider0| has all domains initialized. - Mock::VerifyAndClearExpectations(&provider1_); - Mock::VerifyAndClearExpectations(&provider2_); - EXPECT_CALL(provider1_, IsInitializationComplete(_)) - .WillRepeatedly(Return(false)); - EXPECT_CALL(provider2_, IsInitializationComplete(_)) - .WillRepeatedly(Return(false)); - PolicyServiceImpl::Providers providers; - providers.push_back(&provider0_); - providers.push_back(&provider1_); - providers.push_back(&provider2_); - policy_service_.reset(new PolicyServiceImpl( - providers, PolicyServiceImpl::PreprocessCallback())); - EXPECT_FALSE(policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - EXPECT_FALSE( - policy_service_->IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)); - - // |provider2_| still doesn't have POLICY_DOMAIN_CHROME initialized, so - // the initialization status of that domain won't change. - MockPolicyServiceObserver observer; - policy_service_->AddObserver(POLICY_DOMAIN_CHROME, &observer); - policy_service_->AddObserver(POLICY_DOMAIN_EXTENSIONS, &observer); - EXPECT_CALL(observer, OnPolicyServiceInitialized(_)).Times(0); - Mock::VerifyAndClearExpectations(&provider1_); - EXPECT_CALL(provider1_, IsInitializationComplete(POLICY_DOMAIN_CHROME)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(provider1_, IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)) - .WillRepeatedly(Return(false)); - const PolicyMap kPolicyMap; - provider1_.UpdateChromePolicy(kPolicyMap); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_FALSE(policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - EXPECT_FALSE( - policy_service_->IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)); - - // Same if |provider1_| doesn't have POLICY_DOMAIN_EXTENSIONS initialized. - EXPECT_CALL(observer, OnPolicyServiceInitialized(_)).Times(0); - Mock::VerifyAndClearExpectations(&provider2_); - EXPECT_CALL(provider2_, IsInitializationComplete(POLICY_DOMAIN_CHROME)) - .WillRepeatedly(Return(false)); - EXPECT_CALL(provider2_, IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)) - .WillRepeatedly(Return(true)); - provider2_.UpdateChromePolicy(kPolicyMap); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_FALSE(policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - EXPECT_FALSE( - policy_service_->IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)); - - // Now initialize POLICY_DOMAIN_CHROME on all the providers. - EXPECT_CALL(observer, OnPolicyServiceInitialized(POLICY_DOMAIN_CHROME)); - Mock::VerifyAndClearExpectations(&provider2_); - EXPECT_CALL(provider2_, IsInitializationComplete(POLICY_DOMAIN_CHROME)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(provider2_, IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)) - .WillRepeatedly(Return(true)); - provider2_.UpdateChromePolicy(kPolicyMap); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_TRUE(policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - // Other domains are still not initialized. - EXPECT_FALSE( - policy_service_->IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)); - - // Initialize the remaining domain. - EXPECT_CALL(observer, OnPolicyServiceInitialized(POLICY_DOMAIN_EXTENSIONS)); - Mock::VerifyAndClearExpectations(&provider1_); - EXPECT_CALL(provider1_, IsInitializationComplete(POLICY_DOMAIN_CHROME)) - .WillRepeatedly(Return(true)); - EXPECT_CALL(provider1_, IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)) - .WillRepeatedly(Return(true)); - provider1_.UpdateChromePolicy(kPolicyMap); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_TRUE(policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); - EXPECT_TRUE( - policy_service_->IsInitializationComplete(POLICY_DOMAIN_EXTENSIONS)); - - // Cleanup. - policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, &observer); - policy_service_->RemoveObserver(POLICY_DOMAIN_EXTENSIONS, &observer); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_service_stub.cc b/chrome/browser/policy/policy_service_stub.cc deleted file mode 100644 index c25b50f..0000000 --- a/chrome/browser/policy/policy_service_stub.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_service_stub.h" - -#include "base/message_loop/message_loop.h" - -namespace policy { - -PolicyServiceStub::PolicyServiceStub() {} - -PolicyServiceStub::~PolicyServiceStub() {} - -void PolicyServiceStub::AddObserver(PolicyDomain domain, - Observer* observer) {} - -void PolicyServiceStub::RemoveObserver(PolicyDomain domain, - Observer* observer) {} - -const PolicyMap& PolicyServiceStub::GetPolicies( - const PolicyNamespace& ns) const { - return kEmpty_; -}; - -bool PolicyServiceStub::IsInitializationComplete(PolicyDomain domain) const { - return true; -} - -void PolicyServiceStub::RefreshPolicies(const base::Closure& callback) { - if (!callback.is_null()) - callback.Run(); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_service_stub.h b/chrome/browser/policy/policy_service_stub.h deleted file mode 100644 index 30c2f51..0000000 --- a/chrome/browser/policy/policy_service_stub.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_SERVICE_STUB_H_ -#define CHROME_BROWSER_POLICY_POLICY_SERVICE_STUB_H_ - -#include "base/basictypes.h" -#include "chrome/browser/policy/policy_service.h" -#include "components/policy/core/common/policy_map.h" - -namespace policy { - -// A stub implementation, that is used when ENABLE_CONFIGURATION_POLICY is not -// set. This allows client code to compile without requiring #ifdefs. -class PolicyServiceStub : public PolicyService { - public: - PolicyServiceStub(); - virtual ~PolicyServiceStub(); - - virtual void AddObserver(PolicyDomain domain, - Observer* observer) OVERRIDE; - - virtual void RemoveObserver(PolicyDomain domain, - Observer* observer) OVERRIDE; - - virtual const PolicyMap& GetPolicies( - const PolicyNamespace& ns) const OVERRIDE; - - virtual bool IsInitializationComplete(PolicyDomain domain) const OVERRIDE; - - virtual void RefreshPolicies(const base::Closure& callback) OVERRIDE; - private: - const PolicyMap kEmpty_; - - DISALLOW_COPY_AND_ASSIGN(PolicyServiceStub); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_SERVICE_STUB_H_ diff --git a/chrome/browser/policy/policy_statistics_collector.cc b/chrome/browser/policy/policy_statistics_collector.cc deleted file mode 100644 index 51fe04c..0000000 --- a/chrome/browser/policy/policy_statistics_collector.cc +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/policy_statistics_collector.h" - -#include <algorithm> -#include <string> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/metrics/sparse_histogram.h" -#include "base/prefs/pref_registry_simple.h" -#include "base/prefs/pref_service.h" -#include "base/task_runner.h" -#include "chrome/browser/policy/policy_service.h" -#include "components/policy/core/common/policy_pref_names.h" - -namespace policy { - -const int PolicyStatisticsCollector::kStatisticsUpdateRate = - 24 * 60 * 60 * 1000; // 24 hours. - -PolicyStatisticsCollector::PolicyStatisticsCollector( - const GetChromePolicyDetailsCallback& get_details, - const Schema& chrome_schema, - PolicyService* policy_service, - PrefService* prefs, - const scoped_refptr<base::TaskRunner>& task_runner) - : get_details_(get_details), - chrome_schema_(chrome_schema), - policy_service_(policy_service), - prefs_(prefs), - task_runner_(task_runner) { -} - -PolicyStatisticsCollector::~PolicyStatisticsCollector() { -} - -void PolicyStatisticsCollector::Initialize() { - using base::Time; - using base::TimeDelta; - - TimeDelta update_rate = TimeDelta::FromMilliseconds(kStatisticsUpdateRate); - Time last_update = Time::FromInternalValue( - prefs_->GetInt64(policy_prefs::kLastPolicyStatisticsUpdate)); - TimeDelta delay = std::max(Time::Now() - last_update, TimeDelta::FromDays(0)); - if (delay >= update_rate) - CollectStatistics(); - else - ScheduleUpdate(update_rate - delay); -} - -// static -void PolicyStatisticsCollector::RegisterPrefs(PrefRegistrySimple* registry) { - registry->RegisterInt64Pref(policy_prefs::kLastPolicyStatisticsUpdate, 0); -} - -void PolicyStatisticsCollector::RecordPolicyUse(int id) { - UMA_HISTOGRAM_SPARSE_SLOWLY("Enterprise.Policies", id); -} - -void PolicyStatisticsCollector::CollectStatistics() { - const PolicyMap& policies = policy_service_->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - - // Collect statistics. - for (Schema::Iterator it(chrome_schema_.GetPropertiesIterator()); - !it.IsAtEnd(); it.Advance()) { - if (policies.Get(it.key())) { - const PolicyDetails* details = get_details_.Run(it.key()); - if (details) - RecordPolicyUse(details->id); - else - NOTREACHED(); - } - } - - // Take care of next update. - prefs_->SetInt64(policy_prefs::kLastPolicyStatisticsUpdate, - base::Time::Now().ToInternalValue()); - ScheduleUpdate(base::TimeDelta::FromMilliseconds(kStatisticsUpdateRate)); -} - -void PolicyStatisticsCollector::ScheduleUpdate(base::TimeDelta delay) { - update_callback_.Reset(base::Bind( - &PolicyStatisticsCollector::CollectStatistics, - base::Unretained(this))); - task_runner_->PostDelayedTask(FROM_HERE, update_callback_.callback(), delay); -} - -} // namespace policy diff --git a/chrome/browser/policy/policy_statistics_collector.h b/chrome/browser/policy/policy_statistics_collector.h deleted file mode 100644 index e0444cc..0000000 --- a/chrome/browser/policy/policy_statistics_collector.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_POLICY_STATISTICS_COLLECTOR_H_ -#define CHROME_BROWSER_POLICY_POLICY_STATISTICS_COLLECTOR_H_ - -#include "base/basictypes.h" -#include "base/cancelable_callback.h" -#include "base/memory/ref_counted.h" -#include "base/time/time.h" -#include "components/policy/core/common/policy_details.h" -#include "components/policy/core/common/schema.h" - -class PrefService; -class PrefRegistrySimple; - -namespace base { -class TaskRunner; -} - -namespace policy { - -class PolicyService; - -// Manages regular updates of policy usage UMA histograms. -class PolicyStatisticsCollector { - public: - // Policy usage statistics update rate, in milliseconds. - static const int kStatisticsUpdateRate; - - // Neither |policy_service| nor |prefs| can be NULL and must stay valid - // throughout the lifetime of PolicyStatisticsCollector. - PolicyStatisticsCollector(const GetChromePolicyDetailsCallback& get_details, - const Schema& chrome_schema, - PolicyService* policy_service, - PrefService* prefs, - const scoped_refptr<base::TaskRunner>& task_runner); - virtual ~PolicyStatisticsCollector(); - - // Completes initialization and starts periodical statistic updates. - void Initialize(); - - static void RegisterPrefs(PrefRegistrySimple* registry); - - protected: - // protected virtual for mocking. - virtual void RecordPolicyUse(int id); - - private: - void CollectStatistics(); - void ScheduleUpdate(base::TimeDelta delay); - - GetChromePolicyDetailsCallback get_details_; - Schema chrome_schema_; - PolicyService* policy_service_; - PrefService* prefs_; - - base::CancelableClosure update_callback_; - - const scoped_refptr<base::TaskRunner> task_runner_; - - DISALLOW_COPY_AND_ASSIGN(PolicyStatisticsCollector); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_POLICY_STATISTICS_COLLECTOR_H_ diff --git a/chrome/browser/policy/policy_statistics_collector_unittest.cc b/chrome/browser/policy/policy_statistics_collector_unittest.cc deleted file mode 100644 index dbffb06..0000000 --- a/chrome/browser/policy/policy_statistics_collector_unittest.cc +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <cstring> -#include <string> - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/prefs/pref_registry_simple.h" -#include "base/prefs/testing_pref_service.h" -#include "base/test/test_simple_task_runner.h" -#include "base/values.h" -#include "chrome/browser/policy/mock_policy_service.h" -#include "chrome/browser/policy/policy_statistics_collector.h" -#include "chrome/browser/policy/test/policy_test_utils.h" -#include "components/policy/core/common/external_data_fetcher.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_pref_names.h" -#include "components/policy/core/common/policy_types.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { - -namespace { - -using testing::ReturnRef; - -// Arbitrary policy names used for testing. -const char kTestPolicy1[] = "Test Policy 1"; -const char kTestPolicy2[] = "Test Policy 2"; - -const int kTestPolicy1Id = 42; -const int kTestPolicy2Id = 123; - -const char kTestChromeSchema[] = - "{" - " \"type\": \"object\"," - " \"properties\": {" - " \"Test Policy 1\": { \"type\": \"string\" }," - " \"Test Policy 2\": { \"type\": \"string\" }" - " }" - "}"; - -const PolicyDetails kTestPolicyDetails[] = { - // is_deprecated is_device_policy id max_external_data_size - { false, false, kTestPolicy1Id, 0 }, - { false, false, kTestPolicy2Id, 0 }, -}; - -class TestPolicyStatisticsCollector : public PolicyStatisticsCollector { - public: - TestPolicyStatisticsCollector( - const GetChromePolicyDetailsCallback& get_details, - const Schema& chrome_schema, - PolicyService* policy_service, - PrefService* prefs, - const scoped_refptr<base::TaskRunner>& task_runner) - : PolicyStatisticsCollector(get_details, - chrome_schema, - policy_service, - prefs, - task_runner) {} - - MOCK_METHOD1(RecordPolicyUse, void(int)); -}; - -} // namespace - -class PolicyStatisticsCollectorTest : public testing::Test { - protected: - PolicyStatisticsCollectorTest() - : update_delay_(base::TimeDelta::FromMilliseconds( - PolicyStatisticsCollector::kStatisticsUpdateRate)), - task_runner_(new base::TestSimpleTaskRunner()) { - } - - virtual void SetUp() OVERRIDE { - std::string error; - chrome_schema_ = Schema::Parse(kTestChromeSchema, &error); - ASSERT_TRUE(chrome_schema_.valid()) << error; - - policy_details_.SetDetails(kTestPolicy1, &kTestPolicyDetails[0]); - policy_details_.SetDetails(kTestPolicy2, &kTestPolicyDetails[1]); - - prefs_.registry()->RegisterInt64Pref( - policy_prefs::kLastPolicyStatisticsUpdate, 0); - - // Set up default function behaviour. - EXPECT_CALL(policy_service_, - GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, - std::string()))) - .WillRepeatedly(ReturnRef(policy_map_)); - - // Arbitrary negative value (so it'll be different from |update_delay_|). - last_delay_ = base::TimeDelta::FromDays(-1); - policy_map_.Clear(); - policy_statistics_collector_.reset(new TestPolicyStatisticsCollector( - policy_details_.GetCallback(), - chrome_schema_, - &policy_service_, - &prefs_, - task_runner_)); - } - - void SetPolicy(const std::string& name) { - policy_map_.Set(name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, - base::Value::CreateBooleanValue(true), NULL); - } - - base::TimeDelta GetFirstDelay() const { - if (task_runner_->GetPendingTasks().empty()) { - ADD_FAILURE(); - return base::TimeDelta(); - } - return task_runner_->GetPendingTasks().front().delay; - } - - const base::TimeDelta update_delay_; - - base::TimeDelta last_delay_; - - PolicyDetailsMap policy_details_; - Schema chrome_schema_; - TestingPrefServiceSimple prefs_; - MockPolicyService policy_service_; - PolicyMap policy_map_; - - scoped_refptr<base::TestSimpleTaskRunner> task_runner_; - scoped_ptr<TestPolicyStatisticsCollector> policy_statistics_collector_; -}; - -TEST_F(PolicyStatisticsCollectorTest, CollectPending) { - SetPolicy(kTestPolicy1); - - prefs_.SetInt64(policy_prefs::kLastPolicyStatisticsUpdate, - (base::Time::Now() - update_delay_).ToInternalValue()); - - EXPECT_CALL(*policy_statistics_collector_.get(), - RecordPolicyUse(kTestPolicy1Id)); - - policy_statistics_collector_->Initialize(); - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - EXPECT_EQ(update_delay_, GetFirstDelay()); -} - -TEST_F(PolicyStatisticsCollectorTest, CollectPendingVeryOld) { - SetPolicy(kTestPolicy1); - - // Must not be 0.0 (read comment for Time::FromDoubleT). - prefs_.SetInt64(policy_prefs::kLastPolicyStatisticsUpdate, - base::Time::FromDoubleT(1.0).ToInternalValue()); - - EXPECT_CALL(*policy_statistics_collector_.get(), - RecordPolicyUse(kTestPolicy1Id)); - - policy_statistics_collector_->Initialize(); - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - EXPECT_EQ(update_delay_, GetFirstDelay()); -} - -TEST_F(PolicyStatisticsCollectorTest, CollectLater) { - SetPolicy(kTestPolicy1); - - prefs_.SetInt64(policy_prefs::kLastPolicyStatisticsUpdate, - (base::Time::Now() - update_delay_ / 2).ToInternalValue()); - - policy_statistics_collector_->Initialize(); - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); - EXPECT_LT(GetFirstDelay(), update_delay_); -} - -TEST_F(PolicyStatisticsCollectorTest, MultiplePolicies) { - SetPolicy(kTestPolicy1); - SetPolicy(kTestPolicy2); - - prefs_.SetInt64(policy_prefs::kLastPolicyStatisticsUpdate, - (base::Time::Now() - update_delay_).ToInternalValue()); - - EXPECT_CALL(*policy_statistics_collector_.get(), - RecordPolicyUse(kTestPolicy1Id)); - EXPECT_CALL(*policy_statistics_collector_.get(), - RecordPolicyUse(kTestPolicy2Id)); - - policy_statistics_collector_->Initialize(); - EXPECT_EQ(1u, task_runner_->GetPendingTasks().size()); -} - -} // namespace policy diff --git a/chrome/browser/policy/preg_parser_win.cc b/chrome/browser/policy/preg_parser_win.cc deleted file mode 100644 index a30714a..0000000 --- a/chrome/browser/policy/preg_parser_win.cc +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/preg_parser_win.h" - -#include <windows.h> - -#include <algorithm> -#include <iterator> -#include <vector> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/files/memory_mapped_file.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "base/strings/string16.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/sys_byteorder.h" -#include "base/values.h" -#include "chrome/browser/policy/policy_load_status.h" -#include "components/policy/core/common/registry_dict_win.h" - -namespace policy { -namespace preg_parser { - -const char kPRegFileHeader[8] = - { 'P', 'R', 'e', 'g', '\x01', '\x00', '\x00', '\x00' }; - -// Maximum PReg file size we're willing to accept. -const int64 kMaxPRegFileSize = 1024 * 1024 * 16; - -// Constants for PReg file delimiters. -const char16 kDelimBracketOpen = L'['; -const char16 kDelimBracketClose = L']'; -const char16 kDelimSemicolon = L';'; - -// Registry path separator. -const char16 kRegistryPathSeparator[] = L"\\"; - -// Magic strings for the PReg value field to trigger special actions. -const char kActionTriggerPrefix[] = "**"; -const char kActionTriggerDeleteValues[] = "deletevalues"; -const char kActionTriggerDel[] = "del."; -const char kActionTriggerDelVals[] = "delvals"; -const char kActionTriggerDeleteKeys[] = "deletekeys"; -const char kActionTriggerSecureKey[] = "securekey"; -const char kActionTriggerSoft[] = "soft"; - -// Returns the character at |cursor| and increments it, unless the end is here -// in which case -1 is returned. -int NextChar(const uint8** cursor, const uint8* end) { - // Only read the character if a full char16 is available. - if (*cursor + sizeof(char16) > end) - return -1; - - int result = **cursor | (*(*cursor + 1) << 8); - *cursor += sizeof(char16); - return result; -} - -// Reads a fixed-size field from a PReg file. -bool ReadFieldBinary(const uint8** cursor, - const uint8* end, - uint32 size, - uint8* data) { - if (size == 0) - return true; - - const uint8* field_end = *cursor + size; - if (field_end <= *cursor || field_end > end) - return false; - std::copy(*cursor, field_end, data); - *cursor = field_end; - return true; -} - -bool ReadField32(const uint8** cursor, const uint8* end, uint32* data) { - uint32 value = 0; - if (!ReadFieldBinary(cursor, end, sizeof(uint32), - reinterpret_cast<uint8*>(&value))) { - return false; - } - *data = base::ByteSwapToLE32(value); - return true; -} - -// Reads a string field from a file. -bool ReadFieldString(const uint8** cursor, const uint8* end, string16* str) { - int current = -1; - while ((current = NextChar(cursor, end)) > 0x0000) - *str += current; - - return current == L'\0'; -} - -std::string DecodePRegStringValue(const std::vector<uint8>& data) { - size_t len = data.size() / sizeof(char16); - if (len <= 0) - return std::string(); - - const char16* chars = reinterpret_cast<const char16*>(vector_as_array(&data)); - string16 result; - std::transform(chars, chars + len - 1, std::back_inserter(result), - std::ptr_fun(base::ByteSwapToLE16)); - return UTF16ToUTF8(result); -} - -// Decodes a value from a PReg file given as a uint8 vector. -bool DecodePRegValue(uint32 type, - const std::vector<uint8>& data, - scoped_ptr<base::Value>* value) { - switch (type) { - case REG_SZ: - case REG_EXPAND_SZ: - value->reset(base::Value::CreateStringValue(DecodePRegStringValue(data))); - return true; - case REG_DWORD_LITTLE_ENDIAN: - case REG_DWORD_BIG_ENDIAN: - if (data.size() == sizeof(uint32)) { - uint32 val = *reinterpret_cast<const uint32*>(vector_as_array(&data)); - if (type == REG_DWORD_BIG_ENDIAN) - val = base::NetToHost32(val); - else - val = base::ByteSwapToLE32(val); - value->reset(base::Value::CreateIntegerValue(static_cast<int>(val))); - return true; - } else { - LOG(ERROR) << "Bad data size " << data.size(); - } - break; - case REG_NONE: - case REG_LINK: - case REG_MULTI_SZ: - case REG_RESOURCE_LIST: - case REG_FULL_RESOURCE_DESCRIPTOR: - case REG_RESOURCE_REQUIREMENTS_LIST: - case REG_QWORD_LITTLE_ENDIAN: - default: - LOG(ERROR) << "Unsupported registry data type " << type; - } - - return false; -} - -// Adds the record data passed via parameters to |dict| in case the data is -// relevant policy for Chromium. -void HandleRecord(const string16& key_name, - const string16& value, - uint32 type, - const std::vector<uint8>& data, - RegistryDict* dict) { - // Locate/create the dictionary to place the value in. - std::vector<string16> path; - - Tokenize(key_name, kRegistryPathSeparator, &path); - for (std::vector<string16>::const_iterator entry(path.begin()); - entry != path.end(); ++entry) { - if (entry->empty()) - continue; - const std::string name = UTF16ToUTF8(*entry); - RegistryDict* subdict = dict->GetKey(name); - if (!subdict) { - subdict = new RegistryDict(); - dict->SetKey(name, make_scoped_ptr(subdict)); - } - dict = subdict; - } - - if (value.empty()) - return; - - std::string value_name(UTF16ToUTF8(value)); - if (!StartsWithASCII(value_name, kActionTriggerPrefix, true)) { - scoped_ptr<base::Value> value; - if (DecodePRegValue(type, data, &value)) - dict->SetValue(value_name, value.Pass()); - return; - } - - std::string action_trigger(StringToLowerASCII(value_name.substr( - arraysize(kActionTriggerPrefix) - 1))); - if (action_trigger == kActionTriggerDeleteValues) { - std::vector<std::string> values; - Tokenize(DecodePRegStringValue(data), ";", &values); - for (std::vector<std::string>::const_iterator value(values.begin()); - value != values.end(); ++value) { - dict->RemoveValue(*value); - } - } else if (StartsWithASCII(action_trigger, kActionTriggerDeleteKeys, true)) { - std::vector<std::string> keys; - Tokenize(DecodePRegStringValue(data), ";", &keys); - for (std::vector<std::string>::const_iterator key(keys.begin()); - key != keys.end(); ++key) { - dict->RemoveKey(*key); - } - } else if (StartsWithASCII(action_trigger, kActionTriggerDel, true)) { - dict->RemoveValue( - value_name.substr(arraysize(kActionTriggerPrefix) - 1 + - arraysize(kActionTriggerDel) - 1)); - } else if (StartsWithASCII(action_trigger, kActionTriggerDelVals, true)) { - // Delete all values. - dict->ClearValues(); - } else if (StartsWithASCII(action_trigger, kActionTriggerSecureKey, true) || - StartsWithASCII(action_trigger, kActionTriggerSoft, true)) { - // Doesn't affect values. - } else { - LOG(ERROR) << "Bad action trigger " << value_name; - } -} - -bool ReadFile(const base::FilePath& file_path, - const string16& root, - RegistryDict* dict, - PolicyLoadStatusSample* status) { - base::MemoryMappedFile mapped_file; - if (!mapped_file.Initialize(file_path) || !mapped_file.IsValid()) { - PLOG(ERROR) << "Failed to map " << file_path.value(); - status->Add(POLICY_LOAD_STATUS_READ_ERROR); - return false; - } - - if (mapped_file.length() > kMaxPRegFileSize) { - LOG(ERROR) << "PReg file " << file_path.value() << " too large: " - << mapped_file.length(); - status->Add(POLICY_LOAD_STATUS_TOO_BIG); - return false; - } - - // Check the header. - const int kHeaderSize = arraysize(kPRegFileHeader); - if (mapped_file.length() < kHeaderSize || - memcmp(kPRegFileHeader, mapped_file.data(), kHeaderSize) != 0) { - LOG(ERROR) << "Bad policy file " << file_path.value(); - status->Add(POLICY_LOAD_STATUS_PARSE_ERROR); - return false; - } - - // Parse file contents, which is UCS-2 and little-endian. The latter I - // couldn't find documentation on, but the example I saw were all - // little-endian. It'd be interesting to check on big-endian hardware. - const uint8* cursor = mapped_file.data() + kHeaderSize; - const uint8* end = mapped_file.data() + mapped_file.length(); - while (true) { - if (cursor == end) - return true; - - if (NextChar(&cursor, end) != kDelimBracketOpen) - break; - - // Read the record fields. - string16 key_name; - string16 value; - uint32 type = 0; - uint32 size = 0; - std::vector<uint8> data; - - if (!ReadFieldString(&cursor, end, &key_name)) - break; - - int current = NextChar(&cursor, end); - if (current == kDelimSemicolon) { - if (!ReadFieldString(&cursor, end, &value)) - break; - current = NextChar(&cursor, end); - } - - if (current == kDelimSemicolon) { - if (!ReadField32(&cursor, end, &type)) - break; - current = NextChar(&cursor, end); - } - - if (current == kDelimSemicolon) { - if (!ReadField32(&cursor, end, &size)) - break; - current = NextChar(&cursor, end); - } - - if (current == kDelimSemicolon) { - if (size > kMaxPRegFileSize) - break; - data.resize(size); - if (!ReadFieldBinary(&cursor, end, size, vector_as_array(&data))) - break; - current = NextChar(&cursor, end); - } - - if (current != kDelimBracketClose) - break; - - // Process the record if it is within the |root| subtree. - if (StartsWith(key_name, root, false)) - HandleRecord(key_name.substr(root.size()), value, type, data, dict); - } - - LOG(ERROR) << "Error parsing " << file_path.value() << " at offset " - << reinterpret_cast<const uint8*>(cursor - 1) - mapped_file.data(); - status->Add(POLICY_LOAD_STATUS_PARSE_ERROR); - return false; -} - -} // namespace preg_parser -} // namespace policy diff --git a/chrome/browser/policy/preg_parser_win.h b/chrome/browser/policy/preg_parser_win.h deleted file mode 100644 index dbd54c7..0000000 --- a/chrome/browser/policy/preg_parser_win.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file provides a parser for PReg files which are used for storing group -// policy settings in the file system. The file format is documented here: -// -// http://msdn.microsoft.com/en-us/library/windows/desktop/aa374407(v=vs.85).aspx - -#ifndef CHROME_BROWSER_POLICY_PREG_PARSER_WIN_H_ -#define CHROME_BROWSER_POLICY_PREG_PARSER_WIN_H_ - -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" - -namespace base { -class FilePath; -} - -namespace policy { - -class PolicyLoadStatusSample; -class RegistryDict; - -namespace preg_parser { - -// The magic header in PReg files: ASCII "PReg" + version (0x0001). -extern const char kPRegFileHeader[8]; - -// Reads the PReg file at |file_path| and writes the registry data to |dict|. -// |root| specifies the registry subtree the caller is interested in, -// everything else gets ignored. -bool ReadFile(const base::FilePath& file_path, - const string16& root, - RegistryDict* dict, - PolicyLoadStatusSample* status); - -} // namespace preg_parser -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_PREG_PARSER_WIN_H_ diff --git a/chrome/browser/policy/preg_parser_win_unittest.cc b/chrome/browser/policy/preg_parser_win_unittest.cc deleted file mode 100644 index ede4e97..0000000 --- a/chrome/browser/policy/preg_parser_win_unittest.cc +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/preg_parser_win.h" - -#include "base/base_paths.h" -#include "base/files/file_path.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/path_service.h" -#include "base/values.h" -#include "chrome/browser/policy/policy_load_status.h" -#include "components/policy/core/common/registry_dict_win.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { -namespace preg_parser { -namespace { - -// Check whether two RegistryDicts equal each other. -testing::AssertionResult RegistryDictEquals(const RegistryDict& a, - const RegistryDict& b) { - RegistryDict::KeyMap::const_iterator iter_key_a(a.keys().begin()); - RegistryDict::KeyMap::const_iterator iter_key_b(b.keys().begin()); - for (; iter_key_a != a.keys().end() && iter_key_b != b.keys().end(); - ++iter_key_a, ++iter_key_b) { - if (iter_key_a->first != iter_key_b->first) { - return testing::AssertionFailure() - << "Key mismatch " << iter_key_a->first - << " vs. " << iter_key_b->first; - } - testing::AssertionResult result = RegistryDictEquals(*iter_key_a->second, - *iter_key_b->second); - if (!result) - return result; - } - - RegistryDict::ValueMap::const_iterator iter_value_a(a.values().begin()); - RegistryDict::ValueMap::const_iterator iter_value_b(b.values().begin()); - for (; iter_value_a != a.values().end() && iter_value_b != b.values().end(); - ++iter_value_a, ++iter_value_b) { - if (iter_value_a->first != iter_value_b->first || - !base::Value::Equals(iter_value_a->second, iter_value_b->second)) { - return testing::AssertionFailure() - << "Value mismatch " - << iter_value_a->first << "=" << *iter_value_a->second - << " vs. " << iter_value_b->first << "=" << *iter_value_b->second; - } - } - - return testing::AssertionSuccess(); -} - -void SetInteger(RegistryDict* dict, - const std::string& name, - int value) { - dict->SetValue( - name, - make_scoped_ptr<base::Value>(new base::FundamentalValue(value))); -} - -void SetString(RegistryDict* dict, - const std::string& name, - const std::string& value) { - dict->SetValue( - name, - make_scoped_ptr<base::Value>(new base::StringValue(value))); -} - -TEST(PRegParserWinTest, TestParseFile) { - base::FilePath test_data_dir; - ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir)); - - // Prepare the test dictionary with some data so the test can check that the - // PReg action triggers work, i.e. remove these items. - RegistryDict dict; - SetInteger(&dict, "DeleteValuesTest1", 1); - SetString(&dict, "DeleteValuesTest2", "2"); - dict.SetKey("DeleteKeysTest1", make_scoped_ptr(new RegistryDict())); - scoped_ptr<RegistryDict> delete_keys_test(new RegistryDict()); - SetInteger(delete_keys_test.get(), "DeleteKeysTest2Entry", 1); - dict.SetKey("DeleteKeysTest2", delete_keys_test.Pass()); - SetInteger(&dict, "DelTest", 1); - scoped_ptr<RegistryDict> subdict(new RegistryDict()); - SetInteger(subdict.get(), "DelValsTest1", 1); - SetString(subdict.get(), "DelValsTest2", "2"); - subdict->SetKey("DelValsTest3", make_scoped_ptr(new RegistryDict())); - dict.SetKey("DelValsTest", subdict.Pass()); - - // Run the parser. - base::FilePath test_file( - test_data_dir.AppendASCII("chrome/test/data/policy/registry.pol")); - PolicyLoadStatusSample status; - ASSERT_TRUE(preg_parser::ReadFile( - test_file, L"SOFTWARE\\Policies\\Chromium", &dict, &status)); - - // Build the expected output dictionary. - RegistryDict expected; - scoped_ptr<RegistryDict> del_vals_dict(new RegistryDict()); - del_vals_dict->SetKey("DelValsTest3", make_scoped_ptr(new RegistryDict())); - expected.SetKey("DelValsTest", del_vals_dict.Pass()); - SetInteger(&expected, "HomepageIsNewTabPage", 1); - SetString(&expected, "HomepageLocation", "http://www.example.com"); - SetInteger(&expected, "RestoreOnStartup", 4); - scoped_ptr<RegistryDict> startup_urls(new RegistryDict()); - SetString(startup_urls.get(), "1", "http://www.chromium.org"); - SetString(startup_urls.get(), "2", "http://www.example.com"); - expected.SetKey("RestoreOnStartupURLs", startup_urls.Pass()); - SetInteger(&expected, "ShowHomeButton", 1); - SetString(&expected, "Snowman", "\xE2\x98\x83"); - SetString(&expected, "Empty", ""); - - EXPECT_TRUE(RegistryDictEquals(dict, expected)); -} - -} // namespace -} // namespace preg_parser -} // namespace policy diff --git a/chrome/browser/policy/profile_policy_connector.cc b/chrome/browser/policy/profile_policy_connector.cc index 3344f0e..0b8c02e 100644 --- a/chrome/browser/policy/profile_policy_connector.cc +++ b/chrome/browser/policy/profile_policy_connector.cc @@ -10,11 +10,11 @@ #include "base/logging.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_manager.h" -#include "chrome/browser/policy/policy_service_impl.h" #include "chrome/browser/policy/policy_transformations.h" +#include "components/policy/core/common/cloud/cloud_policy_manager.h" #include "components/policy/core/common/configuration_policy_provider.h" #include "components/policy/core/common/forwarding_policy_provider.h" +#include "components/policy/core/common/policy_service_impl.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/user.h" diff --git a/chrome/browser/policy/profile_policy_connector_stub.cc b/chrome/browser/policy/profile_policy_connector_stub.cc index 4287838..53df341 100644 --- a/chrome/browser/policy/profile_policy_connector_stub.cc +++ b/chrome/browser/policy/profile_policy_connector_stub.cc @@ -4,7 +4,7 @@ #include "chrome/browser/policy/profile_policy_connector.h" -#include "chrome/browser/policy/policy_service_stub.h" +#include "components/policy/core/common/policy_service_stub.h" namespace policy { diff --git a/chrome/browser/policy/test/local_policy_test_server.cc b/chrome/browser/policy/test/local_policy_test_server.cc index 0cc1156..bc1e200 100644 --- a/chrome/browser/policy/test/local_policy_test_server.cc +++ b/chrome/browser/policy/test/local_policy_test_server.cc @@ -15,7 +15,7 @@ #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "crypto/rsa_private_key.h" #include "net/test/python_utils.h" #include "net/test/spawned_test_server/base_test_server.h" diff --git a/chrome/browser/policy/test/policy_test_utils.cc b/chrome/browser/policy/test/policy_test_utils.cc deleted file mode 100644 index 2915abd..0000000 --- a/chrome/browser/policy/test/policy_test_utils.cc +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/policy/test/policy_test_utils.h" - -#include <string> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/json/json_writer.h" -#include "base/logging.h" -#include "base/values.h" -#include "components/policy/core/common/policy_bundle.h" - -namespace policy { - -PolicyDetailsMap::PolicyDetailsMap() {} - -PolicyDetailsMap::~PolicyDetailsMap() {} - -GetChromePolicyDetailsCallback PolicyDetailsMap::GetCallback() const { - return base::Bind(&PolicyDetailsMap::Lookup, base::Unretained(this)); -} - -void PolicyDetailsMap::SetDetails(const std::string& policy, - const PolicyDetails* details) { - map_[policy] = details; -} - -const PolicyDetails* PolicyDetailsMap::Lookup(const std::string& policy) const { - PolicyDetailsMapping::const_iterator it = map_.find(policy); - return it == map_.end() ? NULL : it->second; -} - -bool PolicyServiceIsEmpty(const PolicyService* service) { - const PolicyMap& map = service->GetPolicies( - PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - if (!map.empty()) { - base::DictionaryValue dict; - for (PolicyMap::const_iterator it = map.begin(); it != map.end(); ++it) - dict.SetWithoutPathExpansion(it->first, it->second.value->DeepCopy()); - LOG(WARNING) << "There are pre-existing policies in this machine: " << dict; - } - return map.empty(); -} - -} // namespace policy - -std::ostream& operator<<(std::ostream& os, - const policy::PolicyBundle& bundle) { - os << "{" << std::endl; - for (policy::PolicyBundle::const_iterator iter = bundle.begin(); - iter != bundle.end(); ++iter) { - os << " \"" << iter->first << "\": " << *iter->second << "," << std::endl; - } - os << "}"; - return os; -} - -std::ostream& operator<<(std::ostream& os, policy::PolicyScope scope) { - switch (scope) { - case policy::POLICY_SCOPE_USER: { - os << "POLICY_SCOPE_USER"; - break; - } - case policy::POLICY_SCOPE_MACHINE: { - os << "POLICY_SCOPE_MACHINE"; - break; - } - default: { - os << "POLICY_SCOPE_UNKNOWN(" << int(scope) << ")"; - } - } - return os; -} - -std::ostream& operator<<(std::ostream& os, policy::PolicyLevel level) { - switch (level) { - case policy::POLICY_LEVEL_RECOMMENDED: { - os << "POLICY_LEVEL_RECOMMENDED"; - break; - } - case policy::POLICY_LEVEL_MANDATORY: { - os << "POLICY_LEVEL_MANDATORY"; - break; - } - default: { - os << "POLICY_LEVEL_UNKNOWN(" << int(level) << ")"; - } - } - return os; -} - -std::ostream& operator<<(std::ostream& os, policy::PolicyDomain domain) { - switch (domain) { - case policy::POLICY_DOMAIN_CHROME: { - os << "POLICY_DOMAIN_CHROME"; - break; - } - case policy::POLICY_DOMAIN_EXTENSIONS: { - os << "POLICY_DOMAIN_EXTENSIONS"; - break; - } - default: { - os << "POLICY_DOMAIN_UNKNOWN(" << int(domain) << ")"; - } - } - return os; -} - -std::ostream& operator<<(std::ostream& os, const policy::PolicyMap& policies) { - os << "{" << std::endl; - for (policy::PolicyMap::const_iterator iter = policies.begin(); - iter != policies.end(); ++iter) { - os << " \"" << iter->first << "\": " << iter->second << "," << std::endl; - } - os << "}"; - return os; -} - -std::ostream& operator<<(std::ostream& os, const policy::PolicyMap::Entry& e) { - std::string value; - base::JSONWriter::WriteWithOptions(e.value, - base::JSONWriter::OPTIONS_PRETTY_PRINT, - &value); - os << "{" << std::endl - << " \"level\": " << e.level << "," << std::endl - << " \"scope\": " << e.scope << "," << std::endl - << " \"value\": " << value - << "}"; - return os; -} - -std::ostream& operator<<(std::ostream& os, const policy::PolicyNamespace& ns) { - os << ns.domain << "/" << ns.component_id; - return os; -} diff --git a/chrome/browser/policy/test/policy_test_utils.h b/chrome/browser/policy/test/policy_test_utils.h deleted file mode 100644 index 4ea452e..0000000 --- a/chrome/browser/policy/test/policy_test_utils.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_POLICY_TEST_POLICY_TEST_UTILS_H_ -#define CHROME_BROWSER_POLICY_TEST_POLICY_TEST_UTILS_H_ - -#include <map> -#include <ostream> -#include <string> - -#include "base/basictypes.h" -#include "chrome/browser/policy/policy_service.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_types.h" -#include "policy/policy_constants.h" - -namespace policy { - -class PolicyBundle; -struct PolicyNamespace; - -// A mapping of policy names to PolicyDetails that can be used to set the -// PolicyDetails for test policies. -class PolicyDetailsMap { - public: - PolicyDetailsMap(); - ~PolicyDetailsMap(); - - // The returned callback's lifetime is tied to |this| object. - GetChromePolicyDetailsCallback GetCallback() const; - - // Does not take ownership of |details|. - void SetDetails(const std::string& policy, const PolicyDetails* details); - - private: - typedef std::map<std::string, const PolicyDetails*> PolicyDetailsMapping; - - const PolicyDetails* Lookup(const std::string& policy) const; - - PolicyDetailsMapping map_; - - DISALLOW_COPY_AND_ASSIGN(PolicyDetailsMap); -}; - -// Returns true if |service| is not serving any policies. Otherwise logs the -// current policies and returns false. -bool PolicyServiceIsEmpty(const PolicyService* service); - -} // namespace policy - -std::ostream& operator<<(std::ostream& os, const policy::PolicyBundle& bundle); -std::ostream& operator<<(std::ostream& os, policy::PolicyScope scope); -std::ostream& operator<<(std::ostream& os, policy::PolicyLevel level); -std::ostream& operator<<(std::ostream& os, policy::PolicyDomain domain); -std::ostream& operator<<(std::ostream& os, const policy::PolicyMap& policies); -std::ostream& operator<<(std::ostream& os, const policy::PolicyMap::Entry& e); -std::ostream& operator<<(std::ostream& os, const policy::PolicyNamespace& ns); - -#endif // CHROME_BROWSER_POLICY_TEST_POLICY_TEST_UTILS_H_ diff --git a/chrome/browser/policy/url_blacklist_policy_handler.h b/chrome/browser/policy/url_blacklist_policy_handler.h index 36670fa..a64236b 100644 --- a/chrome/browser/policy/url_blacklist_policy_handler.h +++ b/chrome/browser/policy/url_blacklist_policy_handler.h @@ -7,7 +7,7 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 9e7a065..6b23f8e 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc @@ -105,8 +105,8 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/policy_statistics_collector.h" #include "chrome/browser/policy/url_blacklist_manager.h" +#include "components/policy/core/common/policy_statistics_collector.h" #endif #if defined(ENABLE_MANAGED_USERS) diff --git a/chrome/browser/prefs/chrome_pref_service_factory.cc b/chrome/browser/prefs/chrome_pref_service_factory.cc index 16cd4f8..4976cc6 100644 --- a/chrome/browser/prefs/chrome_pref_service_factory.cc +++ b/chrome/browser/prefs/chrome_pref_service_factory.cc @@ -29,7 +29,7 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "components/policy/core/common/policy_types.h" #endif diff --git a/chrome/browser/prefs/chrome_pref_service_unittest.cc b/chrome/browser/prefs/chrome_pref_service_unittest.cc index d0c7708..ba8a013 100644 --- a/chrome/browser/prefs/chrome_pref_service_unittest.cc +++ b/chrome/browser/prefs/chrome_pref_service_unittest.cc @@ -11,7 +11,6 @@ #include "base/prefs/scoped_user_pref_update.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/prefs/command_line_pref_store.h" #include "chrome/browser/prefs/pref_service_mock_factory.h" @@ -21,6 +20,7 @@ #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_pref_service_syncable.h" #include "chrome/test/base/testing_profile.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/user_prefs/pref_registry_syncable.h" #include "content/public/test/web_contents_tester.h" diff --git a/chrome/browser/prefs/pref_service_syncable_factory.cc b/chrome/browser/prefs/pref_service_syncable_factory.cc index 296b053..ea3c2ad 100644 --- a/chrome/browser/prefs/pref_service_syncable_factory.cc +++ b/chrome/browser/prefs/pref_service_syncable_factory.cc @@ -15,8 +15,8 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/policy_service.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" +#include "components/policy/core/common/policy_service.h" #include "components/policy/core/common/policy_types.h" #endif diff --git a/chrome/browser/prefs/proxy_policy_unittest.cc b/chrome/browser/prefs/proxy_policy_unittest.cc index 1490e11..39824cf 100644 --- a/chrome/browser/prefs/proxy_policy_unittest.cc +++ b/chrome/browser/prefs/proxy_policy_unittest.cc @@ -7,7 +7,6 @@ #include "base/command_line.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" -#include "chrome/browser/policy/policy_service_impl.h" #include "chrome/browser/policy/policy_transformations.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/prefs/pref_service_mock_factory.h" @@ -19,6 +18,7 @@ #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service_impl.h" #include "components/user_prefs/pref_registry_syncable.h" #include "policy/policy_constants.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chrome/browser/profiles/incognito_mode_policy_handler.h b/chrome/browser/profiles/incognito_mode_policy_handler.h index 96b6c4f..6aa8c7e 100644 --- a/chrome/browser/profiles/incognito_mode_policy_handler.h +++ b/chrome/browser/profiles/incognito_mode_policy_handler.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_PROFILES_INCOGNITO_MODE_POLICY_HANDLER_H_ #define CHROME_BROWSER_PROFILES_INCOGNITO_MODE_POLICY_HANDLER_H_ -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/profiles/incognito_mode_policy_handler_unittest.cc b/chrome/browser/profiles/incognito_mode_policy_handler_unittest.cc index 30869cc..acb97eb 100644 --- a/chrome/browser/profiles/incognito_mode_policy_handler_unittest.cc +++ b/chrome/browser/profiles/incognito_mode_policy_handler_unittest.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/configuration_policy_pref_store_unittest.h" +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/incognito_mode_policy_handler.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "grit/generated_resources.h" #include "policy/policy_constants.h" diff --git a/chrome/browser/search_engines/default_search_policy_handler.h b/chrome/browser/search_engines/default_search_policy_handler.h index c0fe715..1dca24d 100644 --- a/chrome/browser/search_engines/default_search_policy_handler.h +++ b/chrome/browser/search_engines/default_search_policy_handler.h @@ -7,7 +7,7 @@ #include <vector> -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { diff --git a/chrome/browser/search_engines/default_search_policy_handler_unittest.cc b/chrome/browser/search_engines/default_search_policy_handler_unittest.cc index 04068ff..49bb3b9 100644 --- a/chrome/browser/search_engines/default_search_policy_handler_unittest.cc +++ b/chrome/browser/search_engines/default_search_policy_handler_unittest.cc @@ -3,10 +3,10 @@ // found in the LICENSE file. #include "base/memory/scoped_ptr.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/configuration_policy_pref_store_unittest.h" +#include "chrome/browser/policy/configuration_policy_pref_store_test.h" #include "chrome/browser/search_engines/default_search_policy_handler.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_pref_store.h" #include "policy/policy_constants.h" namespace policy { diff --git a/chrome/browser/sessions/restore_on_startup_policy_handler.h b/chrome/browser/sessions/restore_on_startup_policy_handler.h index 55ebb2c..6902fa7 100644 --- a/chrome/browser/sessions/restore_on_startup_policy_handler.h +++ b/chrome/browser/sessions/restore_on_startup_policy_handler.h @@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_SESSIONS_RESTORE_ON_STARTUP_POLICY_HANDLER_H_ #define CHROME_BROWSER_SESSIONS_RESTORE_ON_STARTUP_POLICY_HANDLER_H_ -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc b/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc index edfb97e..7e44546 100644 --- a/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc +++ b/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc @@ -10,10 +10,10 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "chrome/browser/policy/configuration_policy_handler.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/sessions/restore_on_startup_policy_handler.h" #include "chrome/common/pref_names.h" +#include "components/policy/core/browser/configuration_policy_handler.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" #include "grit/component_strings.h" diff --git a/chrome/browser/sync/sync_policy_handler.h b/chrome/browser/sync/sync_policy_handler.h index f7080e5..93581c3 100644 --- a/chrome/browser/sync/sync_policy_handler.h +++ b/chrome/browser/sync/sync_policy_handler.h @@ -6,7 +6,7 @@ #define CHROME_BROWSER_SYNC_SYNC_POLICY_HANDLER_H_ #include "base/compiler_specific.h" -#include "chrome/browser/policy/configuration_policy_handler.h" +#include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; diff --git a/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc index 2b595ac..ea65870 100644 --- a/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc @@ -15,9 +15,9 @@ #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" #include "chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.h" -#include "chrome/browser/policy/cloud/message_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" +#include "components/policy/core/browser/cloud/message_util.h" #include "content/public/browser/web_contents.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "google_apis/gaia/gaia_auth_util.h" diff --git a/chrome/browser/ui/webui/options/browser_options_handler.cc b/chrome/browser/ui/webui/options/browser_options_handler.cc index 80f9e8d..b21e156 100644 --- a/chrome/browser/ui/webui/options/browser_options_handler.cc +++ b/chrome/browser/ui/webui/options/browser_options_handler.cc @@ -102,7 +102,6 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/system/timezone_util.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/ui/browser_window.h" @@ -110,6 +109,7 @@ #include "chromeos/dbus/power_manager_client.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" +#include "components/policy/core/common/policy_service.h" #include "policy/policy_constants.h" #include "ui/gfx/image/image_skia.h" #endif // defined(OS_CHROMEOS) diff --git a/chrome/browser/ui/webui/policy_ui.cc b/chrome/browser/ui/webui/policy_ui.cc index 17a1bf5..b5020f5 100644 --- a/chrome/browser/ui/webui/policy_ui.cc +++ b/chrome/browser/ui/webui/policy_ui.cc @@ -18,15 +18,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/policy/browser_policy_connector.h" -#include "chrome/browser/policy/cloud/cloud_policy_client.h" -#include "chrome/browser/policy/cloud/cloud_policy_constants.h" -#include "chrome/browser/policy/cloud/cloud_policy_core.h" -#include "chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h" -#include "chrome/browser/policy/cloud/cloud_policy_store.h" -#include "chrome/browser/policy/cloud/cloud_policy_validator.h" -#include "chrome/browser/policy/cloud/message_util.h" -#include "chrome/browser/policy/configuration_policy_handler_list.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" @@ -34,9 +25,18 @@ #include "chrome/browser/policy/schema_registry_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" +#include "components/policy/core/browser/cloud/message_util.h" +#include "components/policy/core/browser/configuration_policy_handler_list.h" #include "components/policy/core/browser/policy_error_map.h" +#include "components/policy/core/common/cloud/cloud_policy_client.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/core/common/cloud/cloud_policy_core.h" +#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h" +#include "components/policy/core/common/cloud/cloud_policy_store.h" +#include "components/policy/core/common/cloud/cloud_policy_validator.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" +#include "components/policy/core/common/policy_service.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/core/common/schema.h" #include "components/policy/core/common/schema_map.h" diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index ece6e8c..dae192c 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -1459,50 +1459,8 @@ 'browser/policy/autofill_policy_handler.h', 'browser/policy/browser_policy_connector.cc', 'browser/policy/browser_policy_connector.h', - 'browser/policy/cloud/cloud_external_data_manager.cc', - 'browser/policy/cloud/cloud_external_data_manager.h', - 'browser/policy/cloud/cloud_policy_client.cc', - 'browser/policy/cloud/cloud_policy_client.h', - 'browser/policy/cloud/cloud_policy_client_registration_helper.cc', - 'browser/policy/cloud/cloud_policy_client_registration_helper.h', - 'browser/policy/cloud/cloud_policy_constants.cc', - 'browser/policy/cloud/cloud_policy_constants.h', - 'browser/policy/cloud/cloud_policy_core.cc', - 'browser/policy/cloud/cloud_policy_core.h', 'browser/policy/cloud/cloud_policy_invalidator.cc', 'browser/policy/cloud/cloud_policy_invalidator.h', - 'browser/policy/cloud/cloud_policy_manager.cc', - 'browser/policy/cloud/cloud_policy_manager.h', - 'browser/policy/cloud/cloud_policy_refresh_scheduler.cc', - 'browser/policy/cloud/cloud_policy_refresh_scheduler.h', - 'browser/policy/cloud/cloud_policy_service.cc', - 'browser/policy/cloud/cloud_policy_service.h', - 'browser/policy/cloud/cloud_policy_store.cc', - 'browser/policy/cloud/cloud_policy_store.h', - 'browser/policy/cloud/cloud_policy_validator.cc', - 'browser/policy/cloud/cloud_policy_validator.h', - 'browser/policy/cloud/component_cloud_policy_service.cc', - 'browser/policy/cloud/component_cloud_policy_service.h', - 'browser/policy/cloud/component_cloud_policy_store.cc', - 'browser/policy/cloud/component_cloud_policy_store.h', - 'browser/policy/cloud/component_cloud_policy_updater.cc', - 'browser/policy/cloud/component_cloud_policy_updater.h', - 'browser/policy/cloud/device_management_service.cc', - 'browser/policy/cloud/device_management_service.h', - 'browser/policy/cloud/enterprise_metrics.cc', - 'browser/policy/cloud/enterprise_metrics.h', - 'browser/policy/cloud/external_policy_data_fetcher.cc', - 'browser/policy/cloud/external_policy_data_fetcher.h', - 'browser/policy/cloud/external_policy_data_updater.cc', - 'browser/policy/cloud/external_policy_data_updater.h', - 'browser/policy/cloud/message_util.cc', - 'browser/policy/cloud/message_util.h', - 'browser/policy/cloud/rate_limiter.cc', - 'browser/policy/cloud/rate_limiter.h', - 'browser/policy/cloud/resource_cache.cc', - 'browser/policy/cloud/resource_cache.h', - 'browser/policy/cloud/system_policy_request_context.cc', - 'browser/policy/cloud/system_policy_request_context.h', 'browser/policy/cloud/user_cloud_policy_invalidator_factory.cc', 'browser/policy/cloud/user_cloud_policy_invalidator_factory.h', 'browser/policy/cloud/user_cloud_policy_invalidator.cc', @@ -1515,10 +1473,6 @@ 'browser/policy/cloud/user_cloud_policy_store.h', 'browser/policy/cloud/user_cloud_policy_store_base.cc', 'browser/policy/cloud/user_cloud_policy_store_base.h', - 'browser/policy/cloud/user_info_fetcher.cc', - 'browser/policy/cloud/user_info_fetcher.h', - 'browser/policy/cloud/user_policy_request_context.cc', - 'browser/policy/cloud/user_policy_request_context.h', 'browser/policy/cloud/user_policy_signin_service.cc', 'browser/policy/cloud/user_policy_signin_service.h', 'browser/policy/cloud/user_policy_signin_service_android.cc', @@ -1527,40 +1481,16 @@ 'browser/policy/cloud/user_policy_signin_service_base.h', 'browser/policy/cloud/user_policy_signin_service_factory.cc', 'browser/policy/cloud/user_policy_signin_service_factory.h', - 'browser/policy/config_dir_policy_loader.cc', - 'browser/policy/config_dir_policy_loader.h', - 'browser/policy/configuration_policy_handler.cc', - 'browser/policy/configuration_policy_handler.h', 'browser/policy/configuration_policy_handler_android.cc', 'browser/policy/configuration_policy_handler_android.h', - 'browser/policy/configuration_policy_handler_list.cc', - 'browser/policy/configuration_policy_handler_list.h', 'browser/policy/configuration_policy_handler_list_factory.cc', 'browser/policy/configuration_policy_handler_list_factory.h', - 'browser/policy/configuration_policy_pref_store.cc', - 'browser/policy/configuration_policy_pref_store.h', 'browser/policy/file_selection_dialogs_policy_handler.cc', 'browser/policy/file_selection_dialogs_policy_handler.h', 'browser/policy/javascript_policy_handler.cc', 'browser/policy/javascript_policy_handler.h', - 'browser/policy/policy_load_status.cc', - 'browser/policy/policy_load_status.h', - 'browser/policy/policy_loader_mac.cc', - 'browser/policy/policy_loader_mac.h', - 'browser/policy/policy_loader_win.cc', - 'browser/policy/policy_loader_win.h', - 'browser/policy/policy_service.cc', - 'browser/policy/policy_service.h', - 'browser/policy/policy_service_impl.cc', - 'browser/policy/policy_service_impl.h', - 'browser/policy/policy_service_stub.cc', - 'browser/policy/policy_service_stub.h', - 'browser/policy/policy_statistics_collector.cc', - 'browser/policy/policy_statistics_collector.h', 'browser/policy/policy_transformations.cc', 'browser/policy/policy_transformations.h', - 'browser/policy/preg_parser_win.cc', - 'browser/policy/preg_parser_win.h', 'browser/policy/profile_policy_connector.cc', 'browser/policy/profile_policy_connector_stub.cc', 'browser/policy/profile_policy_connector.h', @@ -2845,13 +2775,11 @@ }], ['configuration_policy==1', { 'sources!': [ - 'browser/policy/policy_service_stub.cc', - 'browser/policy/policy_service_stub.h', 'browser/policy/profile_policy_connector_stub.cc', ], 'dependencies': [ 'app/policy/cloud_policy_codegen.gyp:policy', - 'cloud_policy_proto', + '../components/components.gyp:cloud_policy_proto', ], 'conditions': [ ['OS!="android"', { @@ -2875,10 +2803,6 @@ ['exclude', 'browser/sessions/restore_on_startup_policy_handler.h'], ['exclude', 'browser/sync/sync_policy_handler.cc'], ['exclude', 'browser/sync/sync_policy_handler.h'], - ['include', 'browser/policy/policy_service.cc'], - ['include', 'browser/policy/policy_service.h'], - ['include', 'browser/policy/policy_service_stub.cc'], - ['include', 'browser/policy/policy_service_stub.h'], ['include', 'browser/policy/profile_policy_connector_stub.cc'], ['include', 'browser/policy/profile_policy_connector.h'], ['include', 'browser/policy/profile_policy_connector_factory.cc'], @@ -3004,8 +2928,6 @@ 'browser/password_manager/native_backend_kwallet_x.cc', 'browser/password_manager/native_backend_kwallet_x.h', 'browser/platform_util_linux.cc', - 'browser/policy/cloud/cloud_policy_client_registration_helper.cc', - 'browser/policy/cloud/cloud_policy_client_registration_helper.h', 'browser/policy/cloud/user_cloud_policy_manager.cc', 'browser/policy/cloud/user_cloud_policy_manager.h', 'browser/policy/cloud/user_cloud_policy_manager_factory.cc', @@ -3237,7 +3159,6 @@ '../third_party/libusb/libusb.gyp:libusb', ], 'sources': [ - 'browser/policy/cloud/component_cloud_policy_service_stub.cc', 'browser/sessions/in_memory_tab_restore_service.cc', 'browser/sessions/in_memory_tab_restore_service.h', 'browser/signin/android_profile_oauth2_token_service.cc', @@ -3264,21 +3185,8 @@ 'browser/download/download_crx_util.cc', 'browser/net/gaia/gaia_oauth_fetcher.cc', - 'browser/policy/cloud/component_cloud_policy_service.cc', - 'browser/policy/cloud/component_cloud_policy_store.cc', - 'browser/policy/cloud/component_cloud_policy_store.h', - 'browser/policy/cloud/component_cloud_policy_updater.cc', - 'browser/policy/cloud/component_cloud_policy_updater.h', - 'browser/policy/cloud/external_policy_data_fetcher.cc', - 'browser/policy/cloud/external_policy_data_fetcher.h', - 'browser/policy/cloud/external_policy_data_updater.cc', - 'browser/policy/cloud/external_policy_data_updater.h', - 'browser/policy/cloud/resource_cache.cc', - 'browser/policy/cloud/resource_cache.h', 'browser/policy/cloud/user_policy_signin_service.cc', 'browser/policy/cloud/user_policy_signin_service.h', - 'browser/policy/config_dir_policy_loader.cc', - 'browser/policy/config_dir_policy_loader.h', 'browser/sessions/persistent_tab_restore_service.cc', 'browser/sessions/persistent_tab_restore_service.h', 'browser/sessions/session_backend.cc', @@ -3329,7 +3237,6 @@ 'browser/parsers/metadata_parser_jpeg.cc', 'browser/parsers/metadata_parser_jpeg_factory.cc', 'browser/parsers/metadata_parser_manager.cc', - 'browser/policy/policy_load_status.cc', 'browser/policy/proto/cloud/chrome_extension_policy.proto', 'browser/process_singleton.cc', 'browser/process_singleton_modal_dialog_lock.cc', @@ -3639,21 +3546,6 @@ }, 'includes': [ '../build/protoc.gypi' ] }, - { - # Protobuf compiler / generator for cloud policy protocol buffers. - 'target_name': 'cloud_policy_proto', - 'type': 'static_library', - 'sources': [ - 'browser/policy/proto/cloud/chrome_extension_policy.proto', - 'browser/policy/proto/cloud/device_management_backend.proto', - 'browser/policy/proto/cloud/device_management_local.proto', - ], - 'variables': { - 'proto_in_dir': 'browser/policy/proto/cloud', - 'proto_out_dir': 'chrome/browser/policy/proto/cloud', - }, - 'includes': [ '../build/protoc.gypi' ] - }, ], 'conditions': [ ['OS=="android"', { diff --git a/chrome/chrome_browser_chromeos.gypi b/chrome/chrome_browser_chromeos.gypi index c86b07f..ea13afe 100644 --- a/chrome/chrome_browser_chromeos.gypi +++ b/chrome/chrome_browser_chromeos.gypi @@ -31,7 +31,6 @@ 'chrome_resources.gyp:chrome_resources', 'chrome_resources.gyp:platform_locale_settings', 'chrome_resources.gyp:theme_resources', - 'cloud_policy_proto', 'common', 'common/extensions/api/api.gyp:api', 'common_net', @@ -51,6 +50,7 @@ # browser_chromeos #includes power_supply_properties.pb.h directly. '../chromeos/chromeos.gyp:power_manager_proto', '../chromeos/ime/input_method.gyp:gencode', + '../components/components.gyp:cloud_policy_proto', '../components/components.gyp:onc_component', # This depends directly on the variations target, rather than just # transitively via the common target because the proto sources need to diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index 3665de2..10387df 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi @@ -1312,8 +1312,6 @@ 'browser/policy/cloud/device_management_service_browsertest.cc', 'browser/policy/cloud/test_request_interceptor.cc', 'browser/policy/cloud/test_request_interceptor.h', - 'browser/policy/mock_policy_service.cc', - 'browser/policy/mock_policy_service.h', 'browser/policy/policy_browsertest.cc', 'browser/policy/policy_prefs_browsertest.cc', 'browser/prefs/pref_functional_browsertest.cc', diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index 3381ba2..4509877 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi @@ -156,20 +156,8 @@ 'browser/password_manager/password_form_data.h', 'browser/password_manager/test_password_store.cc', 'browser/password_manager/test_password_store.h', - 'browser/policy/cloud/mock_cloud_external_data_manager.cc', - 'browser/policy/cloud/mock_cloud_external_data_manager.h', - 'browser/policy/cloud/mock_cloud_policy_client.cc', - 'browser/policy/cloud/mock_cloud_policy_client.h', - 'browser/policy/cloud/mock_cloud_policy_store.cc', - 'browser/policy/cloud/mock_cloud_policy_store.h', - 'browser/policy/cloud/mock_device_management_service.cc', - 'browser/policy/cloud/mock_device_management_service.h', - 'browser/policy/cloud/policy_builder.cc', - 'browser/policy/cloud/policy_builder.h', 'browser/policy/test/local_policy_test_server.cc', 'browser/policy/test/local_policy_test_server.h', - 'browser/policy/test/policy_test_utils.cc', - 'browser/policy/test/policy_test_utils.h', 'browser/prefs/pref_service_mock_factory.cc', 'browser/prefs/pref_service_mock_factory.h', 'browser/profile_resetter/profile_resetter_test_base.cc', @@ -295,7 +283,6 @@ 'conditions': [ ['OS!="ios"', { 'dependencies': [ - 'cloud_policy_proto', 'common/extensions/api/api.gyp:api', 'plugin', 'renderer', @@ -1096,43 +1083,21 @@ 'browser/plugins/plugin_prefs_unittest.cc', 'browser/policy/autofill_policy_handler_unittest.cc', 'browser/policy/browser_policy_connector_unittest.cc', - 'browser/policy/cloud/cloud_policy_client_unittest.cc', - 'browser/policy/cloud/cloud_policy_core_unittest.cc', 'browser/policy/cloud/cloud_policy_invalidator_unittest.cc', - 'browser/policy/cloud/cloud_policy_manager_unittest.cc', - 'browser/policy/cloud/cloud_policy_refresh_scheduler_unittest.cc', - 'browser/policy/cloud/cloud_policy_service_unittest.cc', - 'browser/policy/cloud/cloud_policy_validator_unittest.cc', - 'browser/policy/cloud/component_cloud_policy_service_unittest.cc', - 'browser/policy/cloud/component_cloud_policy_store_unittest.cc', - 'browser/policy/cloud/component_cloud_policy_updater_unittest.cc', - 'browser/policy/cloud/device_management_service_unittest.cc', - 'browser/policy/cloud/external_policy_data_fetcher_unittest.cc', - 'browser/policy/cloud/external_policy_data_updater_unittest.cc', 'browser/policy/cloud/mock_user_cloud_policy_store.cc', 'browser/policy/cloud/mock_user_cloud_policy_store.h', - 'browser/policy/cloud/rate_limiter_unittest.cc', - 'browser/policy/cloud/resource_cache_unittest.cc', 'browser/policy/cloud/user_cloud_policy_manager_unittest.cc', 'browser/policy/cloud/user_cloud_policy_store_unittest.cc', - 'browser/policy/cloud/user_info_fetcher_unittest.cc', 'browser/policy/cloud/user_policy_signin_service_unittest.cc', - 'browser/policy/config_dir_policy_loader_unittest.cc', 'browser/policy/configuration_policy_handler_unittest.cc', + 'browser/policy/configuration_policy_pref_store_test.cc', + 'browser/policy/configuration_policy_pref_store_test.h', 'browser/policy/configuration_policy_pref_store_unittest.cc', - 'browser/policy/configuration_policy_pref_store_unittest.h', 'browser/policy/file_selection_dialogs_policy_handler_unittest.cc', 'browser/policy/generate_policy_source_unittest.cc', 'browser/policy/javascript_policy_handler_unittest.cc', - 'browser/policy/mock_policy_service.cc', - 'browser/policy/mock_policy_service.h', - 'browser/policy/policy_loader_mac_unittest.cc', - 'browser/policy/policy_loader_win_unittest.cc', 'browser/policy/policy_path_parser_unittest.cc', - 'browser/policy/policy_service_impl_unittest.cc', - 'browser/policy/policy_statistics_collector_unittest.cc', 'browser/policy/policy_transformations_unittest.cc', - 'browser/policy/preg_parser_win_unittest.cc', 'browser/policy/url_blacklist_manager_unittest.cc', 'browser/policy/url_blacklist_policy_handler_unittest.cc', 'browser/predictors/autocomplete_action_predictor_table_unittest.cc', @@ -2597,13 +2562,6 @@ 'browser/extensions/suspicious_extension_bubble_controller_unittest.cc', 'browser/storage_monitor/media_storage_util_unittest.cc', 'browser/net/gaia/gaia_oauth_fetcher_unittest.cc', - 'browser/policy/cloud/component_cloud_policy_service_unittest.cc', - 'browser/policy/cloud/component_cloud_policy_store_unittest.cc', - 'browser/policy/cloud/component_cloud_policy_updater_unittest.cc', - 'browser/policy/cloud/external_policy_data_fetcher_unittest.cc', - 'browser/policy/cloud/external_policy_data_updater_unittest.cc', - 'browser/policy/cloud/resource_cache_unittest.cc', - 'browser/policy/config_dir_policy_loader_unittest.cc', 'browser/policy/policy_path_parser_unittest.cc', 'browser/profiles/off_the_record_profile_impl_unittest.cc', 'browser/profiles/profile_list_desktop_unittest.cc', diff --git a/chrome/test/base/testing_browser_process.cc b/chrome/test/base/testing_browser_process.cc index c119e07..9465f70 100644 --- a/chrome/test/base/testing_browser_process.cc +++ b/chrome/test/base/testing_browser_process.cc @@ -35,7 +35,7 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" #else -#include "chrome/browser/policy/policy_service_stub.h" +#include "components/policy/core/common/policy_service_stub.h" #endif // defined(ENABLE_CONFIGURATION_POLICY) #if defined(ENABLE_FULL_PRINTING) diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index 5b623a4..816e6bc 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc @@ -41,7 +41,6 @@ #include "chrome/browser/net/proxy_service_factory.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" -#include "chrome/browser/policy/policy_service.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/prefs/browser_prefs.h" @@ -61,6 +60,7 @@ #include "chrome/test/base/testing_pref_service_syncable.h" #include "chrome/test/base/ui_test_utils.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" +#include "components/policy/core/common/policy_service.h" #include "components/user_prefs/user_prefs.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" @@ -76,13 +76,13 @@ #include "testing/gmock/include/gmock/gmock.h" #if defined(ENABLE_CONFIGURATION_POLICY) -#include "chrome/browser/policy/policy_service_impl.h" #include "chrome/browser/policy/schema_registry_service.h" #include "chrome/browser/policy/schema_registry_service_factory.h" #include "components/policy/core/common/configuration_policy_provider.h" +#include "components/policy/core/common/policy_service_impl.h" #include "components/policy/core/common/schema.h" #else -#include "chrome/browser/policy/policy_service_stub.h" +#include "components/policy/core/common/policy_service_stub.h" #endif // defined(ENABLE_CONFIGURATION_POLICY) #if defined(ENABLE_MANAGED_USERS) diff --git a/chrome/tools/build/generate_policy_source.py b/chrome/tools/build/generate_policy_source.py index d048c0d..315650d 100755 --- a/chrome/tools/build/generate_policy_source.py +++ b/chrome/tools/build/generate_policy_source.py @@ -617,7 +617,7 @@ CPP_HEAD = ''' #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/values.h" -#include "chrome/browser/policy/cloud/cloud_external_data_manager.h" +#include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "policy/policy_constants.h" |