summaryrefslogtreecommitdiffstats
path: root/chrome/browser/policy/cloud
diff options
context:
space:
mode:
Diffstat (limited to 'chrome/browser/policy/cloud')
-rw-r--r--chrome/browser/policy/cloud/DEPS29
-rw-r--r--chrome/browser/policy/cloud/cloud_external_data_manager.cc40
-rw-r--r--chrome/browser/policy/cloud/cloud_external_data_manager.h74
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_browsertest.cc10
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_client.cc458
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_client.h296
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_client_registration_helper.cc300
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_client_registration_helper.h113
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_client_unittest.cc589
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_constants.cc61
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_constants.h115
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_core.cc84
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_core.h117
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_core_unittest.cc138
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_invalidator.cc6
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_invalidator.h4
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc12
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_manager.cc149
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_manager.h112
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc6
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_manager_unittest.cc354
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.cc375
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_refresh_scheduler.h155
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_refresh_scheduler_unittest.cc493
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_service.cc160
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_service.h113
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_service_unittest.cc240
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_store.cc68
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_store.h164
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_validator.cc382
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_validator.h303
-rw-r--r--chrome/browser/policy/cloud/cloud_policy_validator_unittest.cc297
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc8
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_service.cc515
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_service.h177
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_service_stub.cc56
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_service_unittest.cc554
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_store.cc361
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_store.h144
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_store_unittest.cc325
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_updater.cc109
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_updater.h66
-rw-r--r--chrome/browser/policy/cloud/component_cloud_policy_updater_unittest.cc350
-rw-r--r--chrome/browser/policy/cloud/device_management_service.cc515
-rw-r--r--chrome/browser/policy/cloud/device_management_service.h190
-rw-r--r--chrome/browser/policy/cloud/device_management_service_browsertest.cc6
-rw-r--r--chrome/browser/policy/cloud/device_management_service_unittest.cc704
-rw-r--r--chrome/browser/policy/cloud/enterprise_metrics.cc15
-rw-r--r--chrome/browser/policy/cloud/enterprise_metrics.h200
-rw-r--r--chrome/browser/policy/cloud/external_policy_data_fetcher.cc267
-rw-r--r--chrome/browser/policy/cloud/external_policy_data_fetcher.h182
-rw-r--r--chrome/browser/policy/cloud/external_policy_data_fetcher_unittest.cc496
-rw-r--r--chrome/browser/policy/cloud/external_policy_data_updater.cc400
-rw-r--r--chrome/browser/policy/cloud/external_policy_data_updater.h126
-rw-r--r--chrome/browser/policy/cloud/external_policy_data_updater_unittest.cc962
-rw-r--r--chrome/browser/policy/cloud/message_util.cc125
-rw-r--r--chrome/browser/policy/cloud/message_util.h30
-rw-r--r--chrome/browser/policy/cloud/mock_cloud_external_data_manager.cc27
-rw-r--r--chrome/browser/policy/cloud/mock_cloud_external_data_manager.h45
-rw-r--r--chrome/browser/policy/cloud/mock_cloud_policy_client.cc42
-rw-r--r--chrome/browser/policy/cloud/mock_cloud_policy_client.h77
-rw-r--r--chrome/browser/policy/cloud/mock_cloud_policy_store.cc17
-rw-r--r--chrome/browser/policy/cloud/mock_cloud_policy_store.h48
-rw-r--r--chrome/browser/policy/cloud/mock_device_management_service.cc170
-rw-r--r--chrome/browser/policy/cloud/mock_device_management_service.h81
-rw-r--r--chrome/browser/policy/cloud/policy_builder.cc241
-rw-r--r--chrome/browser/policy/cloud/policy_builder.h140
-rw-r--r--chrome/browser/policy/cloud/rate_limiter.cc58
-rw-r--r--chrome/browser/policy/cloud/rate_limiter.h59
-rw-r--r--chrome/browser/policy/cloud/rate_limiter_unittest.cc121
-rw-r--r--chrome/browser/policy/cloud/resource_cache.cc240
-rw-r--r--chrome/browser/policy/cloud/resource_cache.h96
-rw-r--r--chrome/browser/policy/cloud/resource_cache_unittest.cc157
-rw-r--r--chrome/browser/policy/cloud/system_policy_request_context.cc67
-rw-r--r--chrome/browser/policy/cloud/system_policy_request_context.h48
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc2
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_manager.cc6
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_manager.h2
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc2
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_manager_unittest.cc2
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_store_base.cc4
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_store_base.h4
-rw-r--r--chrome/browser/policy/cloud/user_cloud_policy_store_unittest.cc6
-rw-r--r--chrome/browser/policy/cloud/user_info_fetcher.cc89
-rw-r--r--chrome/browser/policy/cloud/user_info_fetcher.h63
-rw-r--r--chrome/browser/policy/cloud/user_info_fetcher_unittest.cc80
-rw-r--r--chrome/browser/policy/cloud/user_policy_request_context.cc62
-rw-r--r--chrome/browser/policy/cloud/user_policy_request_context.h50
-rw-r--r--chrome/browser/policy/cloud/user_policy_signin_service.cc2
-rw-r--r--chrome/browser/policy/cloud/user_policy_signin_service_android.cc2
-rw-r--r--chrome/browser/policy/cloud/user_policy_signin_service_base.cc6
-rw-r--r--chrome/browser/policy/cloud/user_policy_signin_service_base.h4
-rw-r--r--chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc6
93 files changed, 53 insertions, 14773 deletions
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(&register_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_,
- &registry_,
- &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_,
- &registry_,
- &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, '=', '&', &params_);
- }
-
- 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"