diff options
author | gfeher@chromium.org <gfeher@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-07-09 22:17:33 +0000 |
---|---|---|
committer | gfeher@chromium.org <gfeher@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-07-09 22:17:33 +0000 |
commit | 8a4751337e754922bf46834b8b3c277a4dcdb44b (patch) | |
tree | 7959e4a6a6f6b3ba3b5b8b620901c69e4fffa91b | |
parent | 0a7cbf904d69d1d2a63efe0cb01a49bc5521d405 (diff) | |
download | chromium_src-8a4751337e754922bf46834b8b3c277a4dcdb44b.zip chromium_src-8a4751337e754922bf46834b8b3c277a4dcdb44b.tar.gz chromium_src-8a4751337e754922bf46834b8b3c277a4dcdb44b.tar.bz2 |
Consolidate data storage and notifications in the cloud policy subsystem
Get rid of identity strategies and create a central in-memory data store and notification hub, which is more simple. It's called CloudPolicyDataStore.
BUG=chromium-os:17309
TEST=user and device policies work exactly as before
Review URL: http://codereview.chromium.org/7298012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91957 0039d316-1c4b-4281-b951-d872f2087c98
29 files changed, 590 insertions, 957 deletions
diff --git a/chrome/browser/policy/browser_policy_connector.cc b/chrome/browser/policy/browser_policy_connector.cc index a2d3112..baf2d03 100644 --- a/chrome/browser/policy/browser_policy_connector.cc +++ b/chrome/browser/policy/browser_policy_connector.cc @@ -7,6 +7,7 @@ #include "base/command_line.h" #include "base/path_service.h" #include "chrome/browser/net/gaia/token_service.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/cloud_policy_provider.h" #include "chrome/browser/policy/cloud_policy_provider_impl.h" #include "chrome/browser/policy/cloud_policy_subsystem.h" @@ -15,7 +16,7 @@ #include "chrome/browser/policy/dummy_cloud_policy_provider.h" #include "chrome/browser/policy/dummy_configuration_policy_provider.h" #include "chrome/browser/policy/user_policy_cache.h" -#include "chrome/browser/policy/user_policy_identity_strategy.h" +#include "chrome/browser/policy/user_policy_token_cache.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/gaia/gaia_constants.h" @@ -34,8 +35,6 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/policy/device_policy_cache.h" -#include "chrome/browser/policy/device_policy_identity_strategy.h" -#include "content/common/notification_service.h" #endif namespace policy { @@ -107,14 +106,15 @@ BrowserPolicyConnector::~BrowserPolicyConnector() { if (device_cloud_policy_subsystem_.get()) device_cloud_policy_subsystem_->Shutdown(); device_cloud_policy_subsystem_.reset(); - device_identity_strategy_.reset(); + device_data_store_.reset(); #endif // Shutdown user cloud policy. if (user_cloud_policy_subsystem_.get()) user_cloud_policy_subsystem_->Shutdown(); user_cloud_policy_subsystem_.reset(); - user_identity_strategy_.reset(); + user_data_store_.reset(); + user_policy_token_cache_ = NULL; } ConfigurationPolicyProvider* @@ -181,8 +181,10 @@ void BrowserPolicyConnector::SetDeviceCredentials( const std::string& owner_email, const std::string& gaia_token) { #if defined(OS_CHROMEOS) - if (device_identity_strategy_.get()) - device_identity_strategy_->SetAuthCredentials(owner_email, gaia_token); + if (device_data_store_.get()) { + device_data_store_->set_user_name(owner_email); + device_data_store_->SetGaiaToken(gaia_token); + } #endif } @@ -222,8 +224,10 @@ void BrowserPolicyConnector::DeviceStopAutoRetry() { void BrowserPolicyConnector::FetchDevicePolicy() { #if defined(OS_CHROMEOS) - if (device_identity_strategy_.get()) - return device_identity_strategy_->FetchPolicy(); + if (device_data_store_.get()) { + DCHECK(!device_data_store_->device_token().empty()); + device_data_store_->NotifyDeviceTokenChanged(); + } #endif } @@ -234,7 +238,8 @@ void BrowserPolicyConnector::InitializeUserPolicy(const std::string& user_name, // Throw away the old backend. user_cloud_policy_subsystem_.reset(); - user_identity_strategy_.reset(); + user_data_store_.reset(); + user_policy_token_cache_ = NULL; registrar_.RemoveAll(); CommandLine* command_line = CommandLine::ForCurrentProcess(); @@ -247,26 +252,26 @@ void BrowserPolicyConnector::InitializeUserPolicy(const std::string& user_name, FilePath policy_cache_dir = policy_dir.Append(kPolicyDir); UserPolicyCache* user_policy_cache = new UserPolicyCache(policy_cache_dir.Append(kPolicyCacheFile)); + user_data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies()); + user_policy_token_cache_ = new UserPolicyTokenCache( + user_data_store_->GetWeakPtr(), + policy_cache_dir.Append(kTokenCacheFile)); // Prepending user caches meaning they will take precedence of device policy // caches. managed_cloud_provider_->PrependCache(user_policy_cache); recommended_cloud_provider_->PrependCache(user_policy_cache); - user_identity_strategy_.reset( - new UserPolicyIdentityStrategy( - user_name, - policy_cache_dir.Append(kTokenCacheFile))); user_cloud_policy_subsystem_.reset(new CloudPolicySubsystem( - user_identity_strategy_.get(), + user_data_store_.get(), user_policy_cache)); // Initiate the DM-Token load. - user_identity_strategy_->LoadTokenCache(); + user_policy_token_cache_->Load(); + user_data_store_->set_user_name(user_name); if (token_service_->HasTokenForService( GaiaConstants::kDeviceManagementService)) { - user_identity_strategy_->SetAuthToken( - token_service_->GetTokenForService( + user_data_store_->SetGaiaToken(token_service_->GetTokenForService( GaiaConstants::kDeviceManagementService)); } @@ -294,22 +299,22 @@ void BrowserPolicyConnector::InitializeDevicePolicy() { #if defined(OS_CHROMEOS) // Throw away the old backend. device_cloud_policy_subsystem_.reset(); - device_identity_strategy_.reset(); + device_data_store_.reset(); CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevicePolicy)) { - device_identity_strategy_.reset(new DevicePolicyIdentityStrategy()); + device_data_store_.reset(CloudPolicyDataStore::CreateForDevicePolicies()); install_attributes_.reset(new EnterpriseInstallAttributes( chromeos::CrosLibrary::Get()->GetCryptohomeLibrary())); DevicePolicyCache* device_policy_cache = - new DevicePolicyCache(device_identity_strategy_.get(), + new DevicePolicyCache(device_data_store_.get(), install_attributes_.get()); managed_cloud_provider_->AppendCache(device_policy_cache); recommended_cloud_provider_->AppendCache(device_policy_cache); device_cloud_policy_subsystem_.reset(new CloudPolicySubsystem( - device_identity_strategy_.get(), + device_data_store_.get(), device_policy_cache)); // Initialize the subsystem once the message loops are spinning. @@ -342,8 +347,8 @@ void BrowserPolicyConnector::Observe(NotificationType type, const TokenService::TokenAvailableDetails* token_details = Details<const TokenService::TokenAvailableDetails>(details).ptr(); if (token_details->service() == GaiaConstants::kDeviceManagementService) { - if (user_identity_strategy_.get()) { - user_identity_strategy_->SetAuthToken(token_details->token()); + if (user_data_store_.get()) { + user_data_store_->SetGaiaToken(token_details->token()); } } } else { diff --git a/chrome/browser/policy/browser_policy_connector.h b/chrome/browser/policy/browser_policy_connector.h index 55a2ff9..e58b331 100644 --- a/chrome/browser/policy/browser_policy_connector.h +++ b/chrome/browser/policy/browser_policy_connector.h @@ -9,6 +9,7 @@ #include <string> #include "base/basictypes.h" +#include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/task.h" #include "chrome/browser/policy/enterprise_install_attributes.h" @@ -21,14 +22,11 @@ class TokenService; namespace policy { +class CloudPolicyDataStore; class CloudPolicyProvider; class CloudPolicySubsystem; class ConfigurationPolicyProvider; -class UserPolicyIdentityStrategy; - -#if defined(OS_CHROMEOS) -class DevicePolicyIdentityStrategy; -#endif +class UserPolicyTokenCache; // Manages the lifecycle of browser-global policy infrastructure, such as the // platform policy providers, device- and the user-cloud policy infrastructure. @@ -134,12 +132,13 @@ class BrowserPolicyConnector : public NotificationObserver { scoped_ptr<CloudPolicyProvider> recommended_cloud_provider_; #if defined(OS_CHROMEOS) - scoped_ptr<DevicePolicyIdentityStrategy> device_identity_strategy_; + scoped_ptr<CloudPolicyDataStore> device_data_store_; scoped_ptr<CloudPolicySubsystem> device_cloud_policy_subsystem_; scoped_ptr<EnterpriseInstallAttributes> install_attributes_; #endif - scoped_ptr<UserPolicyIdentityStrategy> user_identity_strategy_; + scoped_refptr<UserPolicyTokenCache> user_policy_token_cache_; + scoped_ptr<CloudPolicyDataStore> user_data_store_; scoped_ptr<CloudPolicySubsystem> user_cloud_policy_subsystem_; ScopedRunnableMethodFactory<BrowserPolicyConnector> method_factory_; diff --git a/chrome/browser/policy/cloud_policy_controller.cc b/chrome/browser/policy/cloud_policy_controller.cc index daef15d..2e7de65 100644 --- a/chrome/browser/policy/cloud_policy_controller.cc +++ b/chrome/browser/policy/cloud_policy_controller.cc @@ -7,22 +7,22 @@ #include <algorithm> #include "base/bind.h" -#include "base/callback.h" #include "base/logging.h" -#include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/rand_util.h" #include "base/string_util.h" #include "chrome/browser/policy/cloud_policy_cache_base.h" #include "chrome/browser/policy/cloud_policy_subsystem.h" -#include "chrome/browser/policy/device_management_backend.h" #include "chrome/browser/policy/device_management_service.h" #include "chrome/browser/policy/enterprise_metrics.h" #include "chrome/browser/policy/proto/device_management_constants.h" +#include "chrome/common/guid.h" + +namespace { // Domain names that are known not to be managed. // We don't register the device when such a user logs in. -static const char* kNonManagedDomains[] = { +const char* kNonManagedDomains[] = { "@googlemail.com", "@gmail.com" }; @@ -30,7 +30,7 @@ static const char* kNonManagedDomains[] = { // Checks the domain part of the given username against the list of known // non-managed domain names. Returns false if |username| is empty or // in a domain known not to be managed. -static bool CanBeInManagedDomain(const std::string& username) { +bool CanBeInManagedDomain(const std::string& username) { if (username.empty()) { // This means incognito user in case of ChromiumOS and // no logged-in user in case of Chromium (SigninService). @@ -44,6 +44,8 @@ static bool CanBeInManagedDomain(const std::string& username) { return true; } +} + namespace policy { namespace em = enterprise_management; @@ -68,19 +70,18 @@ CloudPolicyController::CloudPolicyController( DeviceManagementService* service, CloudPolicyCacheBase* cache, DeviceTokenFetcher* token_fetcher, - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier) { Initialize(service, cache, token_fetcher, - identity_strategy, + data_store, notifier, new DelayedWorkScheduler); } CloudPolicyController::~CloudPolicyController() { - token_fetcher_->RemoveObserver(this); - identity_strategy_->RemoveObserver(this); + data_store_->RemoveObserver(this); scheduler_->CancelDelayedWork(); } @@ -160,37 +161,43 @@ void CloudPolicyController::OnError(DeviceManagementBackend::ErrorCode code) { } } -void CloudPolicyController::OnDeviceTokenAvailable() { - identity_strategy_->OnDeviceTokenAvailable(token_fetcher_->GetDeviceToken()); -} - void CloudPolicyController::OnDeviceTokenChanged() { - if (identity_strategy_->GetDeviceToken().empty()) + if (data_store_->device_token().empty()) SetState(STATE_TOKEN_UNAVAILABLE); else SetState(STATE_TOKEN_VALID); } void CloudPolicyController::OnCredentialsChanged() { - notifier_->Inform(CloudPolicySubsystem::UNENROLLED, - CloudPolicySubsystem::NO_DETAILS, - PolicyNotifier::POLICY_CONTROLLER); - effective_policy_refresh_error_delay_ms_ = - kPolicyRefreshErrorDelayInMilliseconds; - SetState(STATE_TOKEN_UNAVAILABLE); + // This notification is only interesting if we don't have a device token. + // If we already have a device token, that must be matching the current + // user, because (1) we always recreate the policy subsystem after user + // login (2) tokens are cached per user. + if (data_store_->device_token().empty()) { + notifier_->Inform(CloudPolicySubsystem::UNENROLLED, + CloudPolicySubsystem::NO_DETAILS, + PolicyNotifier::POLICY_CONTROLLER); + effective_policy_refresh_error_delay_ms_ = + kPolicyRefreshErrorDelayInMilliseconds; + SetState(STATE_TOKEN_UNAVAILABLE); + } +} + +void CloudPolicyController::OnDataStoreGoingAway() { + NOTREACHED(); } CloudPolicyController::CloudPolicyController( DeviceManagementService* service, CloudPolicyCacheBase* cache, DeviceTokenFetcher* token_fetcher, - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler) { Initialize(service, cache, token_fetcher, - identity_strategy, + data_store, notifier, scheduler); } @@ -199,7 +206,7 @@ void CloudPolicyController::Initialize( DeviceManagementService* service, CloudPolicyCacheBase* cache, DeviceTokenFetcher* token_fetcher, - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler) { DCHECK(cache); @@ -207,33 +214,29 @@ void CloudPolicyController::Initialize( service_ = service; cache_ = cache; token_fetcher_ = token_fetcher; - identity_strategy_ = identity_strategy; + data_store_ = data_store; notifier_ = notifier; state_ = STATE_TOKEN_UNAVAILABLE; policy_refresh_rate_ms_ = kPolicyRefreshRateInMilliseconds; effective_policy_refresh_error_delay_ms_ = kPolicyRefreshErrorDelayInMilliseconds; scheduler_.reset(scheduler); - token_fetcher_->AddObserver(this); - identity_strategy_->AddObserver(this); - if (!identity_strategy_->GetDeviceToken().empty()) + data_store_->AddObserver(this); + if (!data_store_->device_token().empty()) SetState(STATE_TOKEN_VALID); else SetState(STATE_TOKEN_UNAVAILABLE); } void CloudPolicyController::FetchToken() { - std::string username; - std::string auth_token; - std::string device_id = identity_strategy_->GetDeviceID(); - std::string machine_id = identity_strategy_->GetMachineID(); - std::string machine_model = identity_strategy_->GetMachineModel(); - em::DeviceRegisterRequest_Type policy_type = - identity_strategy_->GetPolicyRegisterType(); - if (identity_strategy_->GetCredentials(&username, &auth_token)) { - if (CanBeInManagedDomain(username)) { - token_fetcher_->FetchToken(auth_token, device_id, policy_type, - machine_id, machine_model); + if (data_store_->token_cache_loaded() && + !data_store_->user_name().empty() && + !data_store_->gaia_token().empty()) { + if (CanBeInManagedDomain(data_store_->user_name())) { + // Generate a new random device id. (It'll only be kept if registration + // succeeds.) + data_store_->set_device_id(guid::GenerateGUID()); + token_fetcher_->FetchToken(); } else { SetState(STATE_TOKEN_UNMANAGED); } @@ -242,11 +245,11 @@ void CloudPolicyController::FetchToken() { void CloudPolicyController::SendPolicyRequest() { backend_.reset(service_->CreateBackend()); - DCHECK(!identity_strategy_->GetDeviceToken().empty()); + DCHECK(!data_store_->device_token().empty()); em::DevicePolicyRequest policy_request; em::PolicyFetchRequest* fetch_request = policy_request.add_request(); fetch_request->set_signature_type(em::PolicyFetchRequest::SHA1_RSA); - fetch_request->set_policy_type(identity_strategy_->GetPolicyType()); + fetch_request->set_policy_type(data_store_->policy_type()); if (!cache_->is_unmanaged() && !cache_->last_policy_refresh_time().is_null()) { base::TimeDelta timestamp = @@ -257,8 +260,8 @@ void CloudPolicyController::SendPolicyRequest() { if (cache_->GetPublicKeyVersion(&key_version)) fetch_request->set_public_key_version(key_version); - backend_->ProcessPolicyRequest(identity_strategy_->GetDeviceToken(), - identity_strategy_->GetDeviceID(), + backend_->ProcessPolicyRequest(data_store_->device_token(), + data_store_->device_id(), policy_request, this); } diff --git a/chrome/browser/policy/cloud_policy_controller.h b/chrome/browser/policy/cloud_policy_controller.h index 5b2018f..2872458 100644 --- a/chrome/browser/policy/cloud_policy_controller.h +++ b/chrome/browser/policy/cloud_policy_controller.h @@ -8,20 +8,13 @@ #include <string> -#include "base/file_path.h" +#include "base/basictypes.h" #include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/task.h" -#include "base/time.h" -#include "chrome/browser/policy/cloud_policy_identity_strategy.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/configuration_policy_provider.h" #include "chrome/browser/policy/delayed_work_scheduler.h" -#include "chrome/browser/policy/device_management_backend.h" #include "chrome/browser/policy/device_token_fetcher.h" -class Profile; -class TokenService; - namespace policy { class CloudPolicyCacheBase; @@ -32,14 +25,13 @@ class DeviceManagementBackend; // listens to their callbacks/notifications. class CloudPolicyController : public DeviceManagementBackend::DevicePolicyResponseDelegate, - public DeviceTokenFetcher::Observer, - public CloudPolicyIdentityStrategy::Observer { + public CloudPolicyDataStore::Observer { public: // All parameters are weak pointers. CloudPolicyController(DeviceManagementService* service, CloudPolicyCacheBase* cache, DeviceTokenFetcher* token_fetcher, - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier); virtual ~CloudPolicyController(); @@ -55,15 +47,13 @@ class CloudPolicyController // DevicePolicyResponseDelegate implementation: virtual void HandlePolicyResponse( - const em::DevicePolicyResponse& response); - virtual void OnError(DeviceManagementBackend::ErrorCode code); - - // DeviceTokenFetcher::Observer implementation: - virtual void OnDeviceTokenAvailable(); + const em::DevicePolicyResponse& response) OVERRIDE; + virtual void OnError(DeviceManagementBackend::ErrorCode code) OVERRIDE; - // CloudPolicyIdentityStrategy::Observer implementation: - virtual void OnDeviceTokenChanged(); - virtual void OnCredentialsChanged(); + // CloudPolicyDataStore::Observer implementation: + virtual void OnDeviceTokenChanged() OVERRIDE; + virtual void OnCredentialsChanged() OVERRIDE; + virtual void OnDataStoreGoingAway() OVERRIDE; private: // Indicates the current state the controller is in. @@ -92,7 +82,7 @@ class CloudPolicyController CloudPolicyController(DeviceManagementService* service, CloudPolicyCacheBase* cache, DeviceTokenFetcher* token_fetcher, - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler); @@ -100,7 +90,7 @@ class CloudPolicyController void Initialize(DeviceManagementService* service, CloudPolicyCacheBase* cache, DeviceTokenFetcher* token_fetcher, - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler); @@ -124,7 +114,7 @@ class CloudPolicyController DeviceManagementService* service_; CloudPolicyCacheBase* cache_; - CloudPolicyIdentityStrategy* identity_strategy_; + CloudPolicyDataStore* data_store_; DeviceTokenFetcher* token_fetcher_; scoped_ptr<DeviceManagementBackend> backend_; ControllerState state_; diff --git a/chrome/browser/policy/cloud_policy_controller_unittest.cc b/chrome/browser/policy/cloud_policy_controller_unittest.cc index 7e828db..b358a1f 100644 --- a/chrome/browser/policy/cloud_policy_controller_unittest.cc +++ b/chrome/browser/policy/cloud_policy_controller_unittest.cc @@ -6,68 +6,33 @@ #include "base/message_loop.h" #include "base/scoped_temp_dir.h" -#include "chrome/browser/policy/device_management_service.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/device_token_fetcher.h" #include "chrome/browser/policy/logging_work_scheduler.h" -#include "chrome/browser/policy/mock_configuration_policy_store.h" #include "chrome/browser/policy/mock_device_management_backend.h" #include "chrome/browser/policy/mock_device_management_service.h" #include "chrome/browser/policy/policy_notifier.h" -#include "chrome/browser/policy/proto/device_management_backend.pb.h" #include "chrome/browser/policy/user_policy_cache.h" #include "content/browser/browser_thread.h" #include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -const char kTestToken[] = "cloud_policy_controller_test_auth_token"; - namespace policy { -namespace em = enterprise_management; - using ::testing::_; using ::testing::AtLeast; using ::testing::InSequence; using ::testing::Mock; using ::testing::Return; -class MockCloudPolicyIdentityStrategy : public CloudPolicyIdentityStrategy { - public: - MockCloudPolicyIdentityStrategy() {} - virtual ~MockCloudPolicyIdentityStrategy() {} - - MOCK_METHOD0(GetDeviceToken, std::string()); - MOCK_METHOD0(GetDeviceID, std::string()); - MOCK_METHOD0(GetMachineID, std::string()); - MOCK_METHOD0(GetMachineModel, std::string()); - MOCK_METHOD0(GetPolicyType, std::string()); - MOCK_METHOD0(GetPolicyRegisterType, em::DeviceRegisterRequest_Type()); - - MOCK_METHOD2(GetCredentials, bool(std::string*, std::string*)); - virtual void OnDeviceTokenAvailable(const std::string&) {} - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudPolicyIdentityStrategy); -}; - -ACTION_P2(MockCloudPolicyIdentityStrategyGetCredentials, username, auth_token) { - *arg0 = username; - *arg1 = auth_token; - return true; -} - class MockDeviceTokenFetcher : public DeviceTokenFetcher { public: explicit MockDeviceTokenFetcher(CloudPolicyCacheBase* cache) - : DeviceTokenFetcher(NULL, cache, NULL) {} + : DeviceTokenFetcher(NULL, cache, NULL, NULL) {} virtual ~MockDeviceTokenFetcher() {} - MOCK_METHOD0(GetDeviceToken, const std::string&()); - MOCK_METHOD5(FetchToken, - void(const std::string&, const std::string&, - em::DeviceRegisterRequest_Type, - const std::string&, const std::string&)); + MOCK_METHOD0(FetchToken, void()); MOCK_METHOD0(SetUnmanagedState, void()); private: @@ -88,15 +53,17 @@ class CloudPolicyControllerTest : public testing::Test { temp_user_data_dir_.path().AppendASCII("CloudPolicyControllerTest"))); token_fetcher_.reset(new MockDeviceTokenFetcher(cache_.get())); service_.set_backend(&backend_); + data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies()); } virtual void TearDown() { controller_.reset(); // Unregisters observers. + data_store_.reset(); } void CreateNewController() { controller_.reset(new CloudPolicyController( - &service_, cache_.get(), token_fetcher_.get(), &identity_strategy_, + &service_, cache_.get(), token_fetcher_.get(), data_store_.get(), ¬ifier_, new DummyWorkScheduler)); } @@ -107,33 +74,6 @@ class CloudPolicyControllerTest : public testing::Test { ASSERT_TRUE(Value::Equals(&expected, policy_map->Get(kPolicyDisableSpdy))); } - void SetupIdentityStrategy( - const std::string& device_token, - const std::string& device_id, - const std::string& machine_id, - const std::string& machine_model, - const std::string& policy_type, - const em::DeviceRegisterRequest_Type& policy_register_type, - const std::string& user_name, - const std::string& auth_token) { - EXPECT_CALL(identity_strategy_, GetDeviceToken()).WillRepeatedly( - Return(device_token)); - EXPECT_CALL(identity_strategy_, GetDeviceID()).WillRepeatedly( - Return(device_id)); - EXPECT_CALL(identity_strategy_, GetMachineID()).WillRepeatedly( - Return(machine_id)); - EXPECT_CALL(identity_strategy_, GetMachineModel()).WillRepeatedly( - Return(machine_model)); - EXPECT_CALL(identity_strategy_, GetPolicyType()).WillRepeatedly( - Return(policy_type)); - EXPECT_CALL(identity_strategy_, GetPolicyRegisterType()).WillRepeatedly( - Return(policy_register_type)); - if (!user_name.empty()) { - EXPECT_CALL(identity_strategy_, GetCredentials(_, _)).WillRepeatedly( - MockCloudPolicyIdentityStrategyGetCredentials(user_name, auth_token)); - } - } - void StopMessageLoop() { loop_.QuitNow(); } @@ -142,7 +82,7 @@ class CloudPolicyControllerTest : public testing::Test { scoped_ptr<CloudPolicyCacheBase> cache_; scoped_ptr<CloudPolicyController> controller_; scoped_ptr<MockDeviceTokenFetcher> token_fetcher_; - MockCloudPolicyIdentityStrategy identity_strategy_; + scoped_ptr<CloudPolicyDataStore> data_store_; MockDeviceManagementBackend backend_; MockDeviceManagementService service_; PolicyNotifier notifier_; @@ -159,9 +99,8 @@ class CloudPolicyControllerTest : public testing::Test { // If a device token is present when the controller starts up, it should // fetch and apply policy. TEST_F(CloudPolicyControllerTest, StartupWithDeviceToken) { - SetupIdentityStrategy("fake_device_token", "device_id", "machine_id", - "machine_model", "google/chromeos/user", - em::DeviceRegisterRequest::USER, "", ""); + data_store_->SetupForTesting("fake_device_token", "device_id", "", "", + true); EXPECT_CALL(backend_, ProcessPolicyRequest(_, _, _, _)).WillOnce(DoAll( InvokeWithoutArgs(this, &CloudPolicyControllerTest::StopMessageLoop), MockDeviceManagementBackendSucceedSpdyCloudPolicy())); @@ -173,10 +112,9 @@ TEST_F(CloudPolicyControllerTest, StartupWithDeviceToken) { // If no device token is present when the controller starts up, it should // instruct the token_fetcher_ to fetch one. TEST_F(CloudPolicyControllerTest, StartupWithoutDeviceToken) { - SetupIdentityStrategy("", "device_id", "machine_id", "machine_model", - "google/chromeos/user", em::DeviceRegisterRequest::USER, - "a@b.com", "auth_token"); - EXPECT_CALL(*token_fetcher_.get(), FetchToken(_, _, _, _, _)).Times(1); + data_store_->SetupForTesting("", "device_id", "a@b.com", "auth_token", + true); + EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1); CreateNewController(); loop_.RunAllPending(); } @@ -184,10 +122,9 @@ TEST_F(CloudPolicyControllerTest, StartupWithoutDeviceToken) { // If the current user belongs to a known non-managed domain, no token fetch // should be initiated. TEST_F(CloudPolicyControllerTest, StartupUnmanagedUser) { - SetupIdentityStrategy("", "device_id", "machine_id", "machine_mode", - "google/chromeos/user", em::DeviceRegisterRequest::USER, - "DannoHelper@gmail.com", "auth_token"); - EXPECT_CALL(*token_fetcher_.get(), FetchToken(_, _, _, _, _)).Times(0); + data_store_->SetupForTesting("", "device_id", "DannoHelper@gmail.com", + "auth_token", true); + EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(0); CreateNewController(); loop_.RunAllPending(); } @@ -195,10 +132,9 @@ TEST_F(CloudPolicyControllerTest, StartupUnmanagedUser) { // After policy has been fetched successfully, a new fetch should be triggered // after the refresh interval has timed out. TEST_F(CloudPolicyControllerTest, RefreshAfterSuccessfulPolicy) { - SetupIdentityStrategy("device_token", "device_id", "machine_id", - "machine_model", "google/chromeos/user", - em::DeviceRegisterRequest::USER, - "DannoHelperDelegate@b.com", "auth_token"); + data_store_->SetupForTesting("device_token", "device_id", + "DannoHelperDelegate@b.com", + "auth_token", true); { InSequence s; EXPECT_CALL(backend_, ProcessPolicyRequest(_, _, _, _)).WillOnce( @@ -215,10 +151,9 @@ TEST_F(CloudPolicyControllerTest, RefreshAfterSuccessfulPolicy) { // If policy fetching failed, it should be retried. TEST_F(CloudPolicyControllerTest, RefreshAfterError) { - SetupIdentityStrategy("device_token", "device_id", "machine_id", - "machine_model", "google/chromeos/user", - em::DeviceRegisterRequest::USER, - "DannoHelperDelegateImpl@b.com", "auth_token"); + data_store_->SetupForTesting("device_token", "device_id", + "DannoHelperDelegateImpl@b.com", + "auth_token", true); { InSequence s; EXPECT_CALL(backend_, ProcessPolicyRequest(_, _, _, _)).WillOnce( @@ -237,14 +172,12 @@ TEST_F(CloudPolicyControllerTest, RefreshAfterError) { // If the backend reports that the device token was invalid, the controller // should instruct the token fetcher to fetch a new token. TEST_F(CloudPolicyControllerTest, InvalidToken) { - SetupIdentityStrategy("device_token", "device_id", "machine_id", - "machine_model", "google/chromeos/user", - em::DeviceRegisterRequest::USER, - "standup@ten.am", "auth"); + data_store_->SetupForTesting("device_token", "device_id", + "standup@ten.am", "auth", true); EXPECT_CALL(backend_, ProcessPolicyRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendFailPolicy( DeviceManagementBackend::kErrorServiceManagementTokenInvalid)); - EXPECT_CALL(*token_fetcher_.get(), FetchToken(_, _, _, _, _)).Times(1); + EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1); CreateNewController(); loop_.RunAllPending(); } @@ -252,14 +185,12 @@ TEST_F(CloudPolicyControllerTest, InvalidToken) { // If the backend reports that the device is unknown to the server, the // controller should instruct the token fetcher to fetch a new token. TEST_F(CloudPolicyControllerTest, DeviceNotFound) { - SetupIdentityStrategy("device_token", "device_id", "machine_id", - "machine_model", "google/chromeos/user", - em::DeviceRegisterRequest::USER, - "me@you.com", "auth"); + data_store_->SetupForTesting("device_token", "device_id", + "me@you.com", "auth", true); EXPECT_CALL(backend_, ProcessPolicyRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendFailPolicy( DeviceManagementBackend::kErrorServiceDeviceNotFound)); - EXPECT_CALL(*token_fetcher_.get(), FetchToken(_, _, _, _, _)).Times(1); + EXPECT_CALL(*token_fetcher_.get(), FetchToken()).Times(1); CreateNewController(); loop_.RunAllPending(); } @@ -268,10 +199,8 @@ TEST_F(CloudPolicyControllerTest, DeviceNotFound) { // should instruct the token fetcher to fetch a new token (which will in turn // set and persist the correct 'unmanaged' state). TEST_F(CloudPolicyControllerTest, NoLongerManaged) { - SetupIdentityStrategy("device_token", "device_id", "machine_id", - "machine_model", "google/chromeos/user", - em::DeviceRegisterRequest::USER, - "who@what.com", "auth"); + data_store_->SetupForTesting("device_token", "device_id", + "who@what.com", "auth", true); EXPECT_CALL(backend_, ProcessPolicyRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendFailPolicy( DeviceManagementBackend::kErrorServiceManagementNotSupported)); diff --git a/chrome/browser/policy/cloud_policy_data_store.cc b/chrome/browser/policy/cloud_policy_data_store.cc new file mode 100644 index 0000000..22d8581 --- /dev/null +++ b/chrome/browser/policy/cloud_policy_data_store.cc @@ -0,0 +1,177 @@ +// 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_policy_data_store.h" + +#include "base/compiler_specific.h" +#include "chrome/browser/policy/proto/device_management_backend.pb.h" +#include "chrome/browser/policy/proto/device_management_constants.h" + +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/system_access.h" +#endif + +namespace { + +// MachineInfo key names. +const char kMachineInfoSystemHwqual[] = "hardware_class"; +const char kMachineInfoSerialNumber[] = "serial_number"; + +} // namespace + +namespace policy { + +// static +CloudPolicyDataStore* CloudPolicyDataStore::CreateForUserPolicies() { + return new CloudPolicyDataStore(em::DeviceRegisterRequest::USER, + kChromeUserPolicyType, + "", ""); +} + +// static +CloudPolicyDataStore* CloudPolicyDataStore::CreateForDevicePolicies() { + std::string machine_model; + std::string machine_id; +#if defined(OS_CHROMEOS) + chromeos::SystemAccess* sys_lib = chromeos::SystemAccess::GetInstance(); + if (!sys_lib->GetMachineStatistic(kMachineInfoSystemHwqual, + &machine_model)) { + LOG(ERROR) << "Failed to get machine model."; + } + if (!sys_lib->GetMachineStatistic(kMachineInfoSerialNumber, + &machine_id)) { + LOG(ERROR) << "Failed to get machine serial number."; + } +#endif + return new CloudPolicyDataStore(em::DeviceRegisterRequest::DEVICE, + kChromeDevicePolicyType, + machine_model, + machine_id); +} + +CloudPolicyDataStore::CloudPolicyDataStore( + const em::DeviceRegisterRequest_Type policy_register_type, + const std::string& policy_type, + const std::string& machine_model, + const std::string& machine_id) + : policy_register_type_(policy_register_type), + policy_type_(policy_type), + machine_model_(machine_model), + machine_id_(machine_id), + token_cache_loaded_(false), + ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {} + +CloudPolicyDataStore::~CloudPolicyDataStore() { + FOR_EACH_OBSERVER(Observer, observer_list_, OnDataStoreGoingAway()); +} + +base::WeakPtr<CloudPolicyDataStore> CloudPolicyDataStore::GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); +} + +void CloudPolicyDataStore::SetDeviceToken(const std::string& device_token, + bool from_cache) { + DCHECK(token_cache_loaded_ != from_cache); + if (!token_cache_loaded_) { + // The cache should be the first to set the token. (It may be "") + DCHECK(from_cache); + token_cache_loaded_ = true; + } else { + // The cache should never set the token later. + DCHECK(!from_cache); + } + device_token_ = device_token; + token_cache_loaded_ = true; + NotifyDeviceTokenChanged(); +} + +void CloudPolicyDataStore::SetGaiaToken(const std::string& gaia_token) { + DCHECK(!user_name_.empty()); + gaia_token_ = gaia_token; + NotifyCredentialsChanged(); +} + +void CloudPolicyDataStore::Reset() { + user_name_ = ""; + gaia_token_ = ""; + device_id_ = ""; + device_token_ = ""; +} + +void CloudPolicyDataStore::SetupForTesting(const std::string& device_token, + const std::string& device_id, + const std::string& user_name, + const std::string& gaia_token, + bool token_cache_loaded) { + device_id_ = device_id; + user_name_ = user_name; + gaia_token_ = gaia_token; + device_token_ = device_token; + token_cache_loaded_ = token_cache_loaded; +} + +void CloudPolicyDataStore::set_device_id(const std::string& device_id) { + device_id_ = device_id; +} + +std::string CloudPolicyDataStore::device_id() const { + return device_id_; +} + +void CloudPolicyDataStore::set_user_name(const std::string& user_name) { + user_name_ = user_name; +} + +std::string CloudPolicyDataStore::device_token() const { + return device_token_; +} + +std::string CloudPolicyDataStore::gaia_token() const { + return gaia_token_; +} + +std::string CloudPolicyDataStore::machine_id() const { + return machine_id_; +} + +std::string CloudPolicyDataStore::machine_model() const { + return machine_model_; +} + +em::DeviceRegisterRequest_Type +CloudPolicyDataStore::policy_register_type() const { + return policy_register_type_; +} + +std::string CloudPolicyDataStore::policy_type() const { + return policy_type_; +} + +bool CloudPolicyDataStore::token_cache_loaded() const { + return token_cache_loaded_; +} + +std::string CloudPolicyDataStore::user_name() const { + return user_name_; +} + +void CloudPolicyDataStore::AddObserver( + CloudPolicyDataStore::Observer* observer) { + observer_list_.AddObserver(observer); +} + +void CloudPolicyDataStore::RemoveObserver( + CloudPolicyDataStore::Observer* observer) { + observer_list_.RemoveObserver(observer); +} + +void CloudPolicyDataStore::NotifyCredentialsChanged() { + FOR_EACH_OBSERVER(Observer, observer_list_, OnCredentialsChanged()); +} + +void CloudPolicyDataStore::NotifyDeviceTokenChanged() { + FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenChanged()); +} + +} // namespace policy diff --git a/chrome/browser/policy/cloud_policy_data_store.h b/chrome/browser/policy/cloud_policy_data_store.h new file mode 100644 index 0000000..74327cb --- /dev/null +++ b/chrome/browser/policy/cloud_policy_data_store.h @@ -0,0 +1,126 @@ +// 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. + +#ifndef CHROME_BROWSER_POLICY_CLOUD_POLICY_DATA_STORE_H_ +#define CHROME_BROWSER_POLICY_CLOUD_POLICY_DATA_STORE_H_ +#pragma once + +#include <string> + +#include "base/memory/weak_ptr.h" +#include "base/observer_list.h" +#include "chrome/browser/policy/proto/device_management_backend.pb.h" + +namespace policy { + +namespace em = enterprise_management; + +// Stores in memory all the data that is used in the cloud policy subsystem, +// and manages notification about changes to these fields. +// TODO(gfeher): The policy data stored in CloudPolicyCacheBase is currently +// an exception, move that here. +class CloudPolicyDataStore { + public: + class Observer { + public: + virtual ~Observer() {} + + // Notifies observers that the effective token for fetching policy + // (device_token_, token_cache_loaded_) has changed. + virtual void OnDeviceTokenChanged() = 0; + + // Authentication credentials for talking to the device management service + // (gaia_token_) changed. + virtual void OnCredentialsChanged() = 0; + + // Called from the destructor of CloudPolicyData. + virtual void OnDataStoreGoingAway() = 0; + }; + + // Create CloudPolicyData with constants initialized for fetching user + // policies. + static CloudPolicyDataStore* CreateForUserPolicies(); + + // Create CloudPolicyData with constants initialized for fetching device + // policies. + static CloudPolicyDataStore* CreateForDevicePolicies(); + + virtual ~CloudPolicyDataStore(); + + base::WeakPtr<CloudPolicyDataStore> GetWeakPtr(); + + // Sets the device token, and token_policy_cache_loaded and sends out + // notifications. Also ensures that setting the token should first happen + // from the cache. + void SetDeviceToken(const std::string& device_token, + bool from_cache); + + // Sets the gaia token and sends out notifications. + void SetGaiaToken(const std::string& gaia_token); + + // Clears device and user credentials. + void Reset(); + + // Only used in tests. + void SetupForTesting(const std::string& device_token, + const std::string& device_id, + const std::string& user_name, + const std::string& gaia_token, + bool token_cache_loaded); + + void set_device_id(const std::string& device_id); + void set_user_name(const std::string& user_name); + + std::string device_id() const; + std::string device_token() const; + std::string gaia_token() const; + std::string machine_id() const; + std::string machine_model() const; + em::DeviceRegisterRequest_Type policy_register_type() const; + std::string policy_type() const; + bool token_cache_loaded() const; + std::string user_name() const; + + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + void NotifyCredentialsChanged(); + void NotifyDeviceTokenChanged(); + + private: + CloudPolicyDataStore( + const em::DeviceRegisterRequest_Type policy_register_type, + const std::string& policy_type, + const std::string& machine_model, + const std::string& machine_id); + + // Data necessary for constructing register requests. + std::string gaia_token_; + std::string user_name_; + + // Data necessary for constructing policy requests. + std::string device_token_; + + // Constants that won't change over the life-time of a cloud policy + // subsystem. + const em::DeviceRegisterRequest_Type policy_register_type_; + const std::string policy_type_; + const std::string machine_model_; + const std::string machine_id_; + + // Data used for constructiong both register and policy requests. + std::string device_id_; + + bool token_cache_loaded_; + + ObserverList<Observer, true> observer_list_; + + base::WeakPtrFactory<CloudPolicyDataStore> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(CloudPolicyDataStore); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_POLICY_CLOUD_POLICY_DATA_STORE_H_ diff --git a/chrome/browser/policy/cloud_policy_identity_strategy.cc b/chrome/browser/policy/cloud_policy_identity_strategy.cc deleted file mode 100644 index 6aa80bb..0000000 --- a/chrome/browser/policy/cloud_policy_identity_strategy.cc +++ /dev/null @@ -1,29 +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_policy_identity_strategy.h" - -namespace policy { - -CloudPolicyIdentityStrategy::CloudPolicyIdentityStrategy() {} - -CloudPolicyIdentityStrategy::~CloudPolicyIdentityStrategy() {} - -void CloudPolicyIdentityStrategy::AddObserver(Observer* obs) { - observer_list_.AddObserver(obs); -} - -void CloudPolicyIdentityStrategy::RemoveObserver(Observer* obs) { - observer_list_.RemoveObserver(obs); -} - -void CloudPolicyIdentityStrategy::NotifyDeviceTokenChanged() { - FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenChanged()); -} - -void CloudPolicyIdentityStrategy::NotifyAuthChanged() { - FOR_EACH_OBSERVER(Observer, observer_list_, OnCredentialsChanged()); -} - -} // namespace policy diff --git a/chrome/browser/policy/cloud_policy_identity_strategy.h b/chrome/browser/policy/cloud_policy_identity_strategy.h deleted file mode 100644 index 0b4e213..0000000 --- a/chrome/browser/policy/cloud_policy_identity_strategy.h +++ /dev/null @@ -1,93 +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. - -#ifndef CHROME_BROWSER_POLICY_CLOUD_POLICY_IDENTITY_STRATEGY_H_ -#define CHROME_BROWSER_POLICY_CLOUD_POLICY_IDENTITY_STRATEGY_H_ -#pragma once - -#include <string> - -#include "base/observer_list.h" -#include "chrome/browser/policy/proto/device_management_backend.pb.h" - -namespace policy { - -namespace em = enterprise_management; - -// Manages a device management token, i.e. an identifier that represents a -// registration with the device management service, and the associated -// credentials. Responsibilities include storing and loading the token from -// disk, observing and triggering relevant notifications. -class CloudPolicyIdentityStrategy { - public: - class Observer { - public: - virtual ~Observer() {} - - // Notifies observers that the effective token for fetching policy has - // changed. The token can be queried by calling GetDeviceToken(). - virtual void OnDeviceTokenChanged() = 0; - - // Authentication credentials for talking to the device management service - // changed. New auth data is available through GetCredentials(). - virtual void OnCredentialsChanged() = 0; - }; - - CloudPolicyIdentityStrategy(); - virtual ~CloudPolicyIdentityStrategy(); - - void AddObserver(Observer* obs); - void RemoveObserver(Observer* obs); - - // Returns the device management token, if available. Returns the empty string - // if the device token is currently unavailable. - virtual std::string GetDeviceToken() = 0; - - // Returns the device ID for this device. This is a unique identifier that is - // randomly generated at registration time on the client side. It always has - // to be sent along with the device token to the server. - virtual std::string GetDeviceID() = 0; - - // Returns physical machine ID for this device. - virtual std::string GetMachineID() = 0; - - // Returns physical machine model for this device. - virtual std::string GetMachineModel() = 0; - - // Returns the policy type to be used for registering at the device management - // server. - virtual em::DeviceRegisterRequest_Type GetPolicyRegisterType() = 0; - - // Returns the policy type to be used for requesting policies from the device - // management server. - virtual std::string GetPolicyType() = 0; - - // Retrieves authentication credentials to use when talking to the device - // management service. Returns true if the data is available and writes the - // values to the provided pointers. - virtual bool GetCredentials(std::string* username, - std::string* auth_token) = 0; - - // Notifies the identity strategy that a new token has been fetched. It is up - // to the identity strategy to store the token, decide whether it is going - // to be used, send out an appropriate OnDeviceTokenChanged() notification - // and return the new token in GetDeviceToken() calls. - virtual void OnDeviceTokenAvailable(const std::string& token) = 0; - - protected: - // Notify observers that the effective token has changed. - void NotifyDeviceTokenChanged(); - - // Notify observers about authentication data change. - void NotifyAuthChanged(); - - private: - ObserverList<Observer, true> observer_list_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyIdentityStrategy); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_CLOUD_POLICY_IDENTITY_STRATEGY_H_ diff --git a/chrome/browser/policy/cloud_policy_subsystem.cc b/chrome/browser/policy/cloud_policy_subsystem.cc index ffbcfce..7394fee 100644 --- a/chrome/browser/policy/cloud_policy_subsystem.cc +++ b/chrome/browser/policy/cloud_policy_subsystem.cc @@ -11,7 +11,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/policy/cloud_policy_cache_base.h" #include "chrome/browser/policy/cloud_policy_controller.h" -#include "chrome/browser/policy/cloud_policy_identity_strategy.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/device_management_service.h" #include "chrome/browser/policy/device_token_fetcher.h" #include "chrome/browser/policy/policy_notifier.h" @@ -49,7 +49,7 @@ CloudPolicySubsystem::ObserverRegistrar::~ObserverRegistrar() { } CloudPolicySubsystem::CloudPolicySubsystem( - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, CloudPolicyCacheBase* policy_cache) { std::string device_management_url; CommandLine* command_line = CommandLine::ForCurrentProcess(); @@ -57,7 +57,7 @@ CloudPolicySubsystem::CloudPolicySubsystem( device_management_url = command_line->GetSwitchValueASCII(switches::kDeviceManagementUrl); } - Initialize(identity_strategy, policy_cache, device_management_url); + Initialize(data_store, policy_cache, device_management_url); } CloudPolicySubsystem::~CloudPolicySubsystem() { @@ -76,11 +76,11 @@ void CloudPolicySubsystem::OnIPAddressChanged() { } void CloudPolicySubsystem::Initialize( - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, CloudPolicyCacheBase* policy_cache, const std::string& device_management_url) { device_management_url_ = device_management_url; - identity_strategy_ = identity_strategy; + data_store_ = data_store; net::NetworkChangeNotifier::AddIPAddressObserver(this); notifier_.reset(new PolicyNotifier()); if (!device_management_url_.empty()) { @@ -100,7 +100,6 @@ void CloudPolicySubsystem::CompleteInitialization( DCHECK(device_management_service_.get()); DCHECK(cloud_policy_cache_.get()); DCHECK(device_token_fetcher_.get()); - DCHECK(identity_strategy_); refresh_pref_name_ = refresh_pref_name; CreateCloudPolicyController(); @@ -133,6 +132,7 @@ CloudPolicySubsystem::ErrorDetails CloudPolicySubsystem::error_details() { void CloudPolicySubsystem::StopAutoRetry() { cloud_policy_controller_->StopAutoRetry(); device_token_fetcher_->StopAutoRetry(); + data_store_->Reset(); } // static @@ -179,6 +179,7 @@ void CloudPolicySubsystem::CreateDeviceTokenFetcher() { device_token_fetcher_.reset( new DeviceTokenFetcher(device_management_service_.get(), cloud_policy_cache_.get(), + data_store_, notifier_.get())); } @@ -188,13 +189,11 @@ void CloudPolicySubsystem::CreateCloudPolicyController() { new CloudPolicyController(device_management_service_.get(), cloud_policy_cache_.get(), device_token_fetcher_.get(), - identity_strategy_, + data_store_, notifier_.get())); } CloudPolicySubsystem::CloudPolicySubsystem() - : refresh_pref_name_(NULL), - identity_strategy_(NULL) { -} + : refresh_pref_name_(NULL) {} } // namespace policy diff --git a/chrome/browser/policy/cloud_policy_subsystem.h b/chrome/browser/policy/cloud_policy_subsystem.h index d886216..e839716 100644 --- a/chrome/browser/policy/cloud_policy_subsystem.h +++ b/chrome/browser/policy/cloud_policy_subsystem.h @@ -17,7 +17,7 @@ namespace policy { class CloudPolicyCacheBase; class CloudPolicyController; -class CloudPolicyIdentityStrategy; +class CloudPolicyDataStore; class DeviceManagementService; class DeviceTokenFetcher; class PolicyNotifier; @@ -67,7 +67,7 @@ class CloudPolicySubsystem DISALLOW_COPY_AND_ASSIGN(ObserverRegistrar); }; - CloudPolicySubsystem(CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicySubsystem(CloudPolicyDataStore* data_store, CloudPolicyCacheBase* policy_cache); virtual ~CloudPolicySubsystem(); @@ -103,7 +103,7 @@ class CloudPolicySubsystem CloudPolicySubsystem(); - void Initialize(CloudPolicyIdentityStrategy* identity_strategy, + void Initialize(CloudPolicyDataStore* data_store, CloudPolicyCacheBase* policy_cache, const std::string& device_management_url); @@ -129,8 +129,7 @@ class CloudPolicySubsystem PrefChangeRegistrar pref_change_registrar_; - // Weak reference to pass on to |cloud_policy_controller_| on creation. - CloudPolicyIdentityStrategy* identity_strategy_; + CloudPolicyDataStore* data_store_; // Cloud policy infrastructure stuff. scoped_ptr<PolicyNotifier> notifier_; diff --git a/chrome/browser/policy/cloud_policy_subsystem_unittest.cc b/chrome/browser/policy/cloud_policy_subsystem_unittest.cc index 9d91783..c5b11d7 100644 --- a/chrome/browser/policy/cloud_policy_subsystem_unittest.cc +++ b/chrome/browser/policy/cloud_policy_subsystem_unittest.cc @@ -4,13 +4,13 @@ #include <vector> +#include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/scoped_temp_dir.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/policy/cloud_policy_identity_strategy.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/logging_work_scheduler.h" -#include "chrome/browser/policy/mock_configuration_policy_store.h" #include "chrome/browser/policy/proto/cloud_policy.pb.h" #include "chrome/browser/policy/proto/device_management_backend.pb.h" #include "chrome/browser/policy/testing_cloud_policy_subsystem.h" @@ -22,23 +22,16 @@ #include "content/browser/browser_thread.h" #include "content/common/url_fetcher.h" #include "policy/policy_constants.h" -#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { using ::testing::_; -using ::testing::AtLeast; using ::testing::AtMost; -using ::testing::DoAll; using ::testing::InSequence; -using ::testing::Invoke; -using ::testing::Return; namespace em = enterprise_management; -class CloudPolicySubsystemTest; - namespace { const char kGaiaAuthHeader[] = "GoogleLogin auth=secret123"; @@ -48,64 +41,13 @@ const char kDMToken[] = "token123456"; const char kDeviceManagementUrl[] = "http://localhost:12345/device_management_test"; -// Constant responses of the identity strategy. -const char kMachineId[] = "dummy-cros-machine-123"; -const char kMachineModel[] = "Pony"; -const char kDeviceId[] = "abc-xyz-123"; +// Fake data to be included in requests. const char kUsername[] = "john@smith.com"; const char kAuthToken[] = "secret123"; const char kPolicyType[] = "google/chrome/test"; } // namespace -// A stripped-down identity strategy for the tests. -class TestingIdentityStrategy : public CloudPolicyIdentityStrategy { - public: - TestingIdentityStrategy() { - } - - virtual std::string GetDeviceToken() OVERRIDE { - return device_token_; - } - - virtual std::string GetDeviceID() OVERRIDE { - return kDeviceId; - } - - virtual std::string GetMachineID() OVERRIDE { - return kMachineId; - } - - virtual std::string GetMachineModel() OVERRIDE { - return kMachineModel; - } - - virtual em::DeviceRegisterRequest_Type GetPolicyRegisterType() OVERRIDE { - return em::DeviceRegisterRequest::USER; - } - - virtual std::string GetPolicyType() OVERRIDE { - return kPolicyType; - } - - virtual bool GetCredentials(std::string* username, - std::string* auth_token) OVERRIDE { - *username = kUsername; - *auth_token = kAuthToken;; - return !username->empty() && !auth_token->empty(); - } - - virtual void OnDeviceTokenAvailable(const std::string& token) OVERRIDE { - device_token_ = token; - NotifyDeviceTokenChanged(); - } - - private: - std::string device_token_; - - DISALLOW_COPY_AND_ASSIGN(TestingIdentityStrategy); -}; - // An action that returns an URLRequestJob with an HTTP error code. ACTION_P(CreateFailedResponse, http_error_code) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); @@ -173,13 +115,13 @@ class CloudPolicySubsystemTestBase : public TESTBASE { logger_.reset(new EventLogger); factory_.reset(new TestingPolicyURLFetcherFactory(logger_.get())); URLFetcher::set_factory(factory_.get()); - identity_strategy_.reset(new TestingIdentityStrategy); ASSERT_TRUE(temp_user_data_dir_.CreateUniqueTempDir()); + data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies()); cache_ = new UserPolicyCache( temp_user_data_dir_.path().AppendASCII("CloudPolicyControllerTest")); cloud_policy_subsystem_.reset(new TestingCloudPolicySubsystem( - identity_strategy_.get(), cache_, kDeviceManagementUrl, - logger_.get())); + data_store_.get(), cache_, + kDeviceManagementUrl, logger_.get())); cloud_policy_subsystem_->CompleteInitialization( prefs::kDevicePolicyRefreshRate, 0); } @@ -188,6 +130,7 @@ class CloudPolicySubsystemTestBase : public TESTBASE { ((TestingBrowserProcess*) g_browser_process)->SetLocalState(NULL); cloud_policy_subsystem_->Shutdown(); cloud_policy_subsystem_.reset(); + data_store_.reset(); factory_.reset(); logger_.reset(); prefs_.reset(); @@ -203,6 +146,9 @@ class CloudPolicySubsystemTestBase : public TESTBASE { .WillOnce(InvokeWithoutArgs( this, &CloudPolicySubsystemTestBase::StopMessageLoop)); + data_store_->set_user_name(kUsername); + data_store_->SetGaiaToken(kAuthToken); + data_store_->SetDeviceToken("", true); loop_.RunAllPending(); } @@ -290,7 +236,7 @@ class CloudPolicySubsystemTestBase : public TESTBASE { BrowserThread io_thread_; scoped_ptr<EventLogger> logger_; - scoped_ptr<TestingIdentityStrategy> identity_strategy_; + scoped_ptr<CloudPolicyDataStore> data_store_; scoped_ptr<CloudPolicySubsystem> cloud_policy_subsystem_; scoped_ptr<PrefService> prefs_; CloudPolicyCacheBase* cache_; diff --git a/chrome/browser/policy/delayed_work_scheduler.h b/chrome/browser/policy/delayed_work_scheduler.h index 91b571f..1b03205 100644 --- a/chrome/browser/policy/delayed_work_scheduler.h +++ b/chrome/browser/policy/delayed_work_scheduler.h @@ -19,7 +19,7 @@ class DelayedWorkScheduler { virtual ~DelayedWorkScheduler(); // Cancels the delayed work task. - void CancelDelayedWork(); + virtual void CancelDelayedWork(); // Posts a new delayed task. virtual void PostDelayedWork(const base::Closure& callback, int64 delay); diff --git a/chrome/browser/policy/device_policy_cache.cc b/chrome/browser/policy/device_policy_cache.cc index 6f068bc..a8031ae 100644 --- a/chrome/browser/policy/device_policy_cache.cc +++ b/chrome/browser/policy/device_policy_cache.cc @@ -4,26 +4,25 @@ #include "chrome/browser/policy/device_policy_cache.h" +#include <string> + #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/metrics/histogram.h" -#include "base/task.h" #include "base/values.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/update_library.h" #include "chrome/browser/chromeos/cros_settings_names.h" #include "chrome/browser/chromeos/login/ownership_service.h" #include "chrome/browser/chromeos/user_cros_settings_provider.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/device_policy_identity_strategy.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/enterprise_install_attributes.h" #include "chrome/browser/policy/enterprise_metrics.h" #include "chrome/browser/policy/policy_map.h" #include "chrome/browser/policy/proto/device_management_backend.pb.h" #include "chrome/browser/policy/proto/device_management_constants.h" #include "chrome/browser/policy/proto/device_management_local.pb.h" -#include "content/browser/browser_thread.h" #include "policy/configuration_policy_type.h" namespace { @@ -113,9 +112,9 @@ Value* DecodeIntegerValue(google::protobuf::int64 value) { namespace policy { DevicePolicyCache::DevicePolicyCache( - DevicePolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, EnterpriseInstallAttributes* install_attributes) - : identity_strategy_(identity_strategy), + : data_store_(data_store), install_attributes_(install_attributes), signed_settings_helper_(chromeos::SignedSettingsHelper::Get()), starting_up_(true), @@ -123,10 +122,10 @@ DevicePolicyCache::DevicePolicyCache( } DevicePolicyCache::DevicePolicyCache( - DevicePolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, EnterpriseInstallAttributes* install_attributes, chromeos::SignedSettingsHelper* signed_settings_helper) - : identity_strategy_(identity_strategy), + : data_store_(data_store), install_attributes_(install_attributes), signed_settings_helper_(signed_settings_helper), starting_up_(true), @@ -201,11 +200,15 @@ void DevicePolicyCache::OnRetrievePolicyCompleted( DCHECK(CalledOnValidThread()); if (starting_up_) { starting_up_ = false; + // All the code paths should issue a data_store_->SetDeviceToken(..., true) + // to signal that the cache has finished loading, so other components + // are free to modify token data. if (code == chromeos::SignedSettings::NOT_FOUND || code == chromeos::SignedSettings::KEY_UNAVAILABLE || !policy.has_policy_data()) { InformNotifier(CloudPolicySubsystem::UNENROLLED, CloudPolicySubsystem::NO_DETAILS); + data_store_->SetDeviceToken("", true); return; } em::PolicyData policy_data; @@ -215,6 +218,7 @@ void DevicePolicyCache::OnRetrievePolicyCompleted( kMetricPolicySize); InformNotifier(CloudPolicySubsystem::LOCAL_ERROR, CloudPolicySubsystem::POLICY_LOCAL_ERROR); + data_store_->SetDeviceToken("", true); return; } if (!policy_data.has_request_token() || @@ -225,6 +229,7 @@ void DevicePolicyCache::OnRetrievePolicyCompleted( // TODO(jkummerow): Reminder: When we want to feed device-wide settings // made by a local owner into this cache, we need to call // SetPolicyInternal() here. + data_store_->SetDeviceToken("", true); return; } if (!policy_data.has_username() || !policy_data.has_device_id()) { @@ -232,14 +237,14 @@ void DevicePolicyCache::OnRetrievePolicyCompleted( kMetricPolicySize); InformNotifier(CloudPolicySubsystem::LOCAL_ERROR, CloudPolicySubsystem::POLICY_LOCAL_ERROR); + data_store_->SetDeviceToken("", true); return; } UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyLoadSucceeded, kMetricPolicySize); - identity_strategy_->SetDeviceManagementCredentials( - policy_data.username(), - policy_data.device_id(), - policy_data.request_token()); + data_store_->set_user_name(policy_data.username()); + data_store_->set_device_id(policy_data.device_id()); + data_store_->SetDeviceToken(policy_data.request_token(), true); SetPolicyInternal(policy, NULL, false); } else { // In other words, starting_up_ == false. if (code != chromeos::SignedSettings::SUCCESS) { diff --git a/chrome/browser/policy/device_policy_cache.h b/chrome/browser/policy/device_policy_cache.h index 7e1082d..58b6bc2 100644 --- a/chrome/browser/policy/device_policy_cache.h +++ b/chrome/browser/policy/device_policy_cache.h @@ -6,8 +6,6 @@ #define CHROME_BROWSER_POLICY_DEVICE_POLICY_CACHE_H_ #pragma once -#include <string> - #include "base/memory/scoped_callback_factory.h" #include "chrome/browser/chromeos/login/signed_settings.h" #include "chrome/browser/chromeos/login/signed_settings_helper.h" @@ -16,7 +14,7 @@ namespace policy { -class DevicePolicyIdentityStrategy; +class CloudPolicyDataStore; class EnterpriseInstallAttributes; class PolicyMap; @@ -27,7 +25,7 @@ namespace em = enterprise_management; class DevicePolicyCache : public CloudPolicyCacheBase, public chromeos::SignedSettingsHelper::Callback { public: - explicit DevicePolicyCache(DevicePolicyIdentityStrategy* identity_strategy, + explicit DevicePolicyCache(CloudPolicyDataStore* data_store, EnterpriseInstallAttributes* install_attributes); virtual ~DevicePolicyCache(); @@ -48,7 +46,7 @@ class DevicePolicyCache : public CloudPolicyCacheBase, // Alternate c'tor allowing tests to mock out the SignedSettingsHelper // singleton. DevicePolicyCache( - DevicePolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, EnterpriseInstallAttributes* install_attributes, chromeos::SignedSettingsHelper* signed_settings_helper); @@ -67,7 +65,7 @@ class DevicePolicyCache : public CloudPolicyCacheBase, PolicyMap* mandatory, PolicyMap* recommended); - DevicePolicyIdentityStrategy* identity_strategy_; + CloudPolicyDataStore* data_store_; EnterpriseInstallAttributes* install_attributes_; chromeos::SignedSettingsHelper* signed_settings_helper_; diff --git a/chrome/browser/policy/device_policy_cache_unittest.cc b/chrome/browser/policy/device_policy_cache_unittest.cc index 655e0f3..8346a61 100644 --- a/chrome/browser/policy/device_policy_cache_unittest.cc +++ b/chrome/browser/policy/device_policy_cache_unittest.cc @@ -5,7 +5,7 @@ #include "chrome/browser/policy/device_policy_cache.h" #include "chrome/browser/chromeos/cros/cryptohome_library.h" -#include "chrome/browser/policy/device_policy_identity_strategy.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/enterprise_install_attributes.h" #include "policy/configuration_policy_type.h" #include "testing/gmock/include/gmock/gmock.h" @@ -109,7 +109,8 @@ class DevicePolicyCacheTest : public testing::Test { install_attributes_(cryptohome_.get()) {} virtual void SetUp() { - cache_.reset(new DevicePolicyCache(&identity_strategy_, + data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies()); + cache_.reset(new DevicePolicyCache(data_store_.get(), &install_attributes_, &signed_settings_helper_)); } @@ -134,7 +135,7 @@ class DevicePolicyCacheTest : public testing::Test { scoped_ptr<chromeos::CryptohomeLibrary> cryptohome_; EnterpriseInstallAttributes install_attributes_; - DevicePolicyIdentityStrategy identity_strategy_; + scoped_ptr<CloudPolicyDataStore> data_store_; MockSignedSettingsHelper signed_settings_helper_; scoped_ptr<DevicePolicyCache> cache_; diff --git a/chrome/browser/policy/device_policy_identity_strategy.cc b/chrome/browser/policy/device_policy_identity_strategy.cc deleted file mode 100644 index 909cfbd..0000000 --- a/chrome/browser/policy/device_policy_identity_strategy.cc +++ /dev/null @@ -1,105 +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/device_policy_identity_strategy.h" - -#include "chrome/browser/browser_process.h" -#include "chrome/browser/chromeos/cros/cros_library.h" -#include "chrome/browser/chromeos/login/ownership_service.h" -#include "chrome/browser/chromeos/login/user_manager.h" -#include "chrome/browser/chromeos/system_access.h" -#include "chrome/browser/net/gaia/token_service.h" -#include "chrome/browser/policy/proto/device_management_constants.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/common/guid.h" -#include "chrome/common/net/gaia/gaia_constants.h" -#include "content/common/notification_service.h" -#include "content/common/notification_type.h" - -// MachineInfo key names. -static const char kMachineInfoSystemHwqual[] = "hardware_class"; -static const char kMachineInfoSerialNumber[] = "serial_number"; - -namespace policy { - -DevicePolicyIdentityStrategy::DevicePolicyIdentityStrategy() { - chromeos::SystemAccess* sys_lib = chromeos::SystemAccess::GetInstance(); - - if (!sys_lib->GetMachineStatistic(kMachineInfoSystemHwqual, - &machine_model_)) { - LOG(ERROR) << "Failed to get machine model."; - } - if (!sys_lib->GetMachineStatistic(kMachineInfoSerialNumber, - &machine_id_)) { - LOG(ERROR) << "Failed to get machine serial number."; - } -} - -DevicePolicyIdentityStrategy::~DevicePolicyIdentityStrategy() { -} - -std::string DevicePolicyIdentityStrategy::GetDeviceToken() { - return device_token_; -} - -std::string DevicePolicyIdentityStrategy::GetDeviceID() { - return device_id_; -} - -std::string DevicePolicyIdentityStrategy::GetMachineID() { - return machine_id_; -} - -std::string DevicePolicyIdentityStrategy::GetMachineModel() { - return machine_model_; -} - -em::DeviceRegisterRequest_Type -DevicePolicyIdentityStrategy::GetPolicyRegisterType() { - return em::DeviceRegisterRequest::DEVICE; -} - -std::string DevicePolicyIdentityStrategy::GetPolicyType() { - return kChromeDevicePolicyType; -} - -void DevicePolicyIdentityStrategy::SetAuthCredentials( - const std::string& username, - const std::string& auth_token) { - username_ = username; - auth_token_ = auth_token; - device_id_ = guid::GenerateGUID(); - NotifyAuthChanged(); -} - -void DevicePolicyIdentityStrategy::SetDeviceManagementCredentials( - const std::string& owner_email, - const std::string& device_id, - const std::string& device_token) { - username_ = owner_email; - device_id_ = device_id; - device_token_ = device_token; - NotifyDeviceTokenChanged(); -} - -void DevicePolicyIdentityStrategy::FetchPolicy() { - DCHECK(!device_token_.empty()); - NotifyDeviceTokenChanged(); -} - -bool DevicePolicyIdentityStrategy::GetCredentials(std::string* username, - std::string* auth_token) { - *username = username_; - *auth_token = auth_token_; - - return !username->empty() && !auth_token->empty(); -} - -void DevicePolicyIdentityStrategy::OnDeviceTokenAvailable( - const std::string& token) { - device_token_ = token; -} - -} // namespace policy diff --git a/chrome/browser/policy/device_policy_identity_strategy.h b/chrome/browser/policy/device_policy_identity_strategy.h deleted file mode 100644 index c849dff..0000000 --- a/chrome/browser/policy/device_policy_identity_strategy.h +++ /dev/null @@ -1,74 +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. - -#ifndef CHROME_BROWSER_POLICY_DEVICE_POLICY_IDENTITY_STRATEGY_H_ -#define CHROME_BROWSER_POLICY_DEVICE_POLICY_IDENTITY_STRATEGY_H_ -#pragma once - -#include <string> - -#include "base/compiler_specific.h" -#include "chrome/browser/policy/cloud_policy_identity_strategy.h" - -class TokenService; - -namespace policy { - -// DM token provider that stores the token in CrOS signed settings. -class DevicePolicyIdentityStrategy : public CloudPolicyIdentityStrategy { - public: - DevicePolicyIdentityStrategy(); - virtual ~DevicePolicyIdentityStrategy(); - - // Sets (GAIA) auth credentials of the owner of the device during device - // enrollment. This automatically triggers fetching a DMToken that can - // be used for future authentication with DMServer. - void SetAuthCredentials(const std::string& username, - const std::string& auth_token); - - // Sets the device's credentials when they have been read from disk after - // a reboot. - void SetDeviceManagementCredentials(const std::string& owner_email, - const std::string& device_id, - const std::string& device_token); - - // Initiates a policy fetch after a successful device registration. This - // function should be called only after the device token has been fetched - // either through the DMServer or loaded from the cache. - void FetchPolicy(); - - // CloudPolicyIdentityStrategy implementation: - virtual std::string GetDeviceToken() OVERRIDE; - virtual std::string GetDeviceID() OVERRIDE; - virtual std::string GetMachineID() OVERRIDE; - virtual std::string GetMachineModel() OVERRIDE; - virtual em::DeviceRegisterRequest_Type GetPolicyRegisterType() OVERRIDE; - virtual std::string GetPolicyType() OVERRIDE; - virtual bool GetCredentials(std::string* username, - std::string* auth_token) OVERRIDE; - virtual void OnDeviceTokenAvailable(const std::string& token) OVERRIDE; - - private: - // The e-mail and auth token of the device owner. Set by |SetCredentials()|. - std::string username_; - std::string auth_token_; - - // The machine identifier and model. - std::string machine_id_; - std::string machine_model_; - - // The device identifier to be sent with requests. (This is actually more like - // a session identifier since it is re-generated for each registration - // request.) - std::string device_id_; - - // Current token. Empty if not available. - std::string device_token_; - - DISALLOW_COPY_AND_ASSIGN(DevicePolicyIdentityStrategy); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_DEVICE_POLICY_IDENTITY_STRATEGY_H_ diff --git a/chrome/browser/policy/device_token_fetcher.cc b/chrome/browser/policy/device_token_fetcher.cc index fe9cbb2..5cb59fc 100644 --- a/chrome/browser/policy/device_token_fetcher.cc +++ b/chrome/browser/policy/device_token_fetcher.cc @@ -8,9 +8,9 @@ #include "base/bind.h" #include "base/callback.h" -#include "base/message_loop.h" #include "base/metrics/histogram.h" #include "chrome/browser/policy/cloud_policy_cache_base.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/device_management_service.h" #include "chrome/browser/policy/enterprise_metrics.h" #include "chrome/browser/policy/proto/device_management_constants.h" @@ -34,9 +34,11 @@ namespace em = enterprise_management; DeviceTokenFetcher::DeviceTokenFetcher( DeviceManagementService* service, CloudPolicyCacheBase* cache, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier) { Initialize(service, cache, + data_store, notifier, new DelayedWorkScheduler); } @@ -44,36 +46,24 @@ DeviceTokenFetcher::DeviceTokenFetcher( DeviceTokenFetcher::DeviceTokenFetcher( DeviceManagementService* service, CloudPolicyCacheBase* cache, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler) { - Initialize(service, - cache, - notifier, - scheduler); + Initialize(service, cache, data_store, notifier, scheduler); } DeviceTokenFetcher::~DeviceTokenFetcher() { scheduler_->CancelDelayedWork(); } -void DeviceTokenFetcher::FetchToken( - const std::string& auth_token, - const std::string& device_id, - em::DeviceRegisterRequest_Type policy_type, - const std::string& machine_id, - const std::string& machine_model) { +void DeviceTokenFetcher::FetchToken() { SetState(STATE_INACTIVE); - auth_token_ = auth_token; - device_id_ = device_id; - policy_type_ = policy_type; - machine_id_ = machine_id; - machine_model_ = machine_model; FetchTokenInternal(); } void DeviceTokenFetcher::FetchTokenInternal() { DCHECK(state_ != STATE_TOKEN_AVAILABLE); - if (auth_token_.empty() || device_id_.empty()) { + if (data_store_->gaia_token().empty() || data_store_->device_id().empty()) { // Maybe this device is unmanaged, just exit. The CloudPolicyController // will call FetchToken() again if something changes. return; @@ -81,12 +71,14 @@ void DeviceTokenFetcher::FetchTokenInternal() { // Construct a new backend, which will discard any previous requests. backend_.reset(service_->CreateBackend()); em::DeviceRegisterRequest request; - request.set_type(policy_type_); - if (!machine_id_.empty()) - request.set_machine_id(machine_id_); - if (!machine_model_.empty()) - request.set_machine_model(machine_model_); - backend_->ProcessRegisterRequest(auth_token_, device_id_, request, this); + request.set_type(data_store_->policy_register_type()); + if (!data_store_->machine_id().empty()) + request.set_machine_id(data_store_->machine_id()); + if (!data_store_->machine_model().empty()) + request.set_machine_model(data_store_->machine_model()); + backend_->ProcessRegisterRequest(data_store_->gaia_token(), + data_store_->device_id(), + request, this); } void DeviceTokenFetcher::SetUnmanagedState() { @@ -97,25 +89,9 @@ void DeviceTokenFetcher::SetUnmanagedState() { SetState(STATE_UNMANAGED); } -const std::string& DeviceTokenFetcher::GetDeviceToken() { - return device_token_; -} - void DeviceTokenFetcher::StopAutoRetry() { scheduler_->CancelDelayedWork(); backend_.reset(); - device_token_.clear(); - auth_token_.clear(); - device_id_.clear(); -} - -void DeviceTokenFetcher::AddObserver(DeviceTokenFetcher::Observer* observer) { - observer_list_.AddObserver(observer); -} - -void DeviceTokenFetcher::RemoveObserver( - DeviceTokenFetcher::Observer* observer) { - observer_list_.RemoveObserver(observer); } void DeviceTokenFetcher::HandleRegisterResponse( @@ -123,7 +99,7 @@ void DeviceTokenFetcher::HandleRegisterResponse( if (response.has_device_management_token()) { UMA_HISTOGRAM_ENUMERATION(kMetricToken, kMetricTokenFetchOK, kMetricTokenSize); - device_token_ = response.device_management_token(); + data_store_->SetDeviceToken(response.device_management_token(), false); SetState(STATE_TOKEN_AVAILABLE); } else { NOTREACHED(); @@ -156,11 +132,13 @@ void DeviceTokenFetcher::OnError(DeviceManagementBackend::ErrorCode code) { void DeviceTokenFetcher::Initialize(DeviceManagementService* service, CloudPolicyCacheBase* cache, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler) { service_ = service; cache_ = cache; notifier_ = notifier; + data_store_ = data_store; effective_token_fetch_error_delay_ms_ = kTokenFetchErrorDelayMilliseconds; state_ = STATE_INACTIVE; scheduler_.reset(scheduler); @@ -177,15 +155,11 @@ void DeviceTokenFetcher::SetState(FetcherState state) { base::Time delayed_work_at; switch (state_) { case STATE_INACTIVE: - device_token_.clear(); - auth_token_.clear(); - device_id_.clear(); notifier_->Inform(CloudPolicySubsystem::UNENROLLED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::TOKEN_FETCHER); break; case STATE_TOKEN_AVAILABLE: - FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenAvailable()); notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::TOKEN_FETCHER); diff --git a/chrome/browser/policy/device_token_fetcher.h b/chrome/browser/policy/device_token_fetcher.h index c714cf3..cec1b93 100644 --- a/chrome/browser/policy/device_token_fetcher.h +++ b/chrome/browser/policy/device_token_fetcher.h @@ -6,11 +6,7 @@ #define CHROME_BROWSER_POLICY_DEVICE_TOKEN_FETCHER_H_ #pragma once -#include <string> - #include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/task.h" #include "chrome/browser/policy/delayed_work_scheduler.h" #include "chrome/browser/policy/device_management_backend.h" #include "chrome/browser/policy/policy_notifier.h" @@ -19,6 +15,7 @@ namespace policy { class CloudPolicyCacheBase; +class CloudPolicyDataStore; class DeviceManagementService; namespace em = enterprise_management; @@ -31,49 +28,34 @@ namespace em = enterprise_management; class DeviceTokenFetcher : public DeviceManagementBackend::DeviceRegisterResponseDelegate { public: - class Observer { - public: - virtual ~Observer() {} - virtual void OnDeviceTokenAvailable() = 0; - }; - // |service| is used to talk to the device management service and |cache| is // used to persist whether the device is unmanaged. DeviceTokenFetcher(DeviceManagementService* service, CloudPolicyCacheBase* cache, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier); // Version for tests that allows to set timing parameters. // Takes ownership of |scheduler|. DeviceTokenFetcher(DeviceManagementService* service, CloudPolicyCacheBase* cache, + CloudPolicyDataStore* data_store, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler); virtual ~DeviceTokenFetcher(); // Starts fetching a token. // Declared virtual so it can be overridden by mocks. - virtual void FetchToken(const std::string& auth_token, - const std::string& device_id, - em::DeviceRegisterRequest_Type policy_type, - const std::string& machine_id, - const std::string& machine_model); + virtual void FetchToken(); virtual void SetUnmanagedState(); - // Returns the device management token or the empty string if not available. - // Declared virtual so it can be overridden by mocks. - virtual const std::string& GetDeviceToken(); - // Disables the auto-retry-on-error behavior of this token fetcher. void StopAutoRetry(); - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - // DeviceManagementBackend::DeviceRegisterResponseDelegate method overrides: virtual void HandleRegisterResponse( - const em::DeviceRegisterResponse& response); - virtual void OnError(DeviceManagementBackend::ErrorCode code); + const em::DeviceRegisterResponse& response) OVERRIDE; + virtual void OnError(DeviceManagementBackend::ErrorCode code) OVERRIDE; private: friend class DeviceTokenFetcherTest; @@ -103,6 +85,7 @@ class DeviceTokenFetcher // Common initialization helper. void Initialize(DeviceManagementService* service, CloudPolicyCacheBase* cache, + CloudPolicyDataStore* data, PolicyNotifier* notifier, DelayedWorkScheduler* scheduler); @@ -135,23 +118,9 @@ class DeviceTokenFetcher // State the fetcher is currently in. FetcherState state_; - // Current device token. - std::string device_token_; - - // Contains the AuthToken for the device management server. - std::string auth_token_; - // Device identifier to send to the server. - std::string device_id_; - // Contains policy type to send to the server. - em::DeviceRegisterRequest_Type policy_type_; - // Contains physical machine id to send to the server. - std::string machine_id_; - // Contains physical machine model to send to server. - std::string machine_model_; + CloudPolicyDataStore* data_store_; scoped_ptr<DelayedWorkScheduler> scheduler_; - - ObserverList<Observer, true> observer_list_; }; } // namespace policy diff --git a/chrome/browser/policy/device_token_fetcher_unittest.cc b/chrome/browser/policy/device_token_fetcher_unittest.cc index 0f9826a..04b23ca 100644 --- a/chrome/browser/policy/device_token_fetcher_unittest.cc +++ b/chrome/browser/policy/device_token_fetcher_unittest.cc @@ -4,19 +4,14 @@ #include "chrome/browser/policy/device_token_fetcher.h" -#include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_temp_dir.h" -#include "chrome/browser/net/gaia/token_service.h" -#include "chrome/browser/policy/device_management_service.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" #include "chrome/browser/policy/logging_work_scheduler.h" #include "chrome/browser/policy/mock_device_management_backend.h" #include "chrome/browser/policy/mock_device_management_service.h" #include "chrome/browser/policy/policy_notifier.h" -#include "chrome/browser/policy/proto/device_management_backend.pb.h" #include "chrome/browser/policy/user_policy_cache.h" -#include "chrome/common/net/gaia/gaia_constants.h" -#include "chrome/test/testing_profile.h" #include "content/browser/browser_thread.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -28,12 +23,14 @@ const char kTestToken[] = "device_token_fetcher_test_auth_token"; using testing::_; using testing::Mock; -class MockTokenAvailableObserver : public DeviceTokenFetcher::Observer { +class MockTokenAvailableObserver : public CloudPolicyDataStore::Observer { public: MockTokenAvailableObserver() {} virtual ~MockTokenAvailableObserver() {} - MOCK_METHOD0(OnDeviceTokenAvailable, void()); + MOCK_METHOD0(OnDeviceTokenChanged, void()); + MOCK_METHOD0(OnCredentialsChanged, void()); + MOCK_METHOD0(OnDataStoreGoingAway, void()); private: DISALLOW_COPY_AND_ASSIGN(MockTokenAvailableObserver); @@ -51,16 +48,27 @@ class DeviceTokenFetcherTest : public testing::Test { cache_.reset(new UserPolicyCache( temp_user_data_dir_.path().AppendASCII("DeviceTokenFetcherTest"))); service_.set_backend(&backend_); + data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies()); + data_store_->AddObserver(&observer_); } virtual void TearDown() { loop_.RunAllPending(); + data_store_->RemoveObserver(&observer_); + } + + void FetchToken(DeviceTokenFetcher* fetcher) { + data_store_->SetupForTesting("", "fake_device_id", "fake_user_name", + "fake_auth_token", true); + fetcher->FetchToken(); } MessageLoop loop_; MockDeviceManagementBackend backend_; MockDeviceManagementService service_; scoped_ptr<CloudPolicyCacheBase> cache_; + scoped_ptr<CloudPolicyDataStore> data_store_; + MockTokenAvailableObserver observer_; PolicyNotifier notifier_; ScopedTempDir temp_user_data_dir_; @@ -73,32 +81,26 @@ TEST_F(DeviceTokenFetcherTest, FetchToken) { testing::InSequence s; EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendSucceedRegister()); - DeviceTokenFetcher fetcher(&service_, cache_.get(), ¬ifier_); - MockTokenAvailableObserver observer; - EXPECT_CALL(observer, OnDeviceTokenAvailable()); - fetcher.AddObserver(&observer); - EXPECT_EQ("", fetcher.GetDeviceToken()); - fetcher.FetchToken("fake_auth_token", "fake_device_id", - em::DeviceRegisterRequest::USER, - "fake_machine_id", "fake_machine_model"); + DeviceTokenFetcher fetcher(&service_, cache_.get(), data_store_.get(), + ¬ifier_); + EXPECT_CALL(observer_, OnDeviceTokenChanged()); + EXPECT_EQ("", data_store_->device_token()); + FetchToken(&fetcher); loop_.RunAllPending(); - Mock::VerifyAndClearExpectations(&observer); - std::string token = fetcher.GetDeviceToken(); + Mock::VerifyAndClearExpectations(&observer_); + std::string token = data_store_->device_token(); EXPECT_NE("", token); // Calling FetchToken() again should result in a new token being fetched. EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendSucceedRegister()); - EXPECT_CALL(observer, OnDeviceTokenAvailable()); - fetcher.FetchToken("fake_auth_token", "fake_device_id", - em::DeviceRegisterRequest::USER, - "fake_machine_id", "fake_machine_model"); + EXPECT_CALL(observer_, OnDeviceTokenChanged()); + FetchToken(&fetcher); loop_.RunAllPending(); - Mock::VerifyAndClearExpectations(&observer); - std::string token2 = fetcher.GetDeviceToken(); + Mock::VerifyAndClearExpectations(&observer_); + std::string token2 = data_store_->device_token(); EXPECT_NE("", token2); EXPECT_NE(token, token2); - fetcher.RemoveObserver(&observer); } TEST_F(DeviceTokenFetcherTest, RetryOnError) { @@ -107,18 +109,13 @@ TEST_F(DeviceTokenFetcherTest, RetryOnError) { MockDeviceManagementBackendFailRegister( DeviceManagementBackend::kErrorRequestFailed)).WillOnce( MockDeviceManagementBackendSucceedRegister()); - DeviceTokenFetcher fetcher(&service_, cache_.get(), ¬ifier_, - new DummyWorkScheduler); - MockTokenAvailableObserver observer; - EXPECT_CALL(observer, OnDeviceTokenAvailable()); - fetcher.AddObserver(&observer); - fetcher.FetchToken("fake_auth_token", "fake_device_id", - em::DeviceRegisterRequest::USER, - "fake_machine_id", "fake_machine_model"); + DeviceTokenFetcher fetcher(&service_, cache_.get(), data_store_.get(), + ¬ifier_, new DummyWorkScheduler); + EXPECT_CALL(observer_, OnDeviceTokenChanged()); + FetchToken(&fetcher); loop_.RunAllPending(); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_NE("", fetcher.GetDeviceToken()); - fetcher.RemoveObserver(&observer); + Mock::VerifyAndClearExpectations(&observer_); + EXPECT_NE("", data_store_->device_token()); } TEST_F(DeviceTokenFetcherTest, UnmanagedDevice) { @@ -126,18 +123,14 @@ TEST_F(DeviceTokenFetcherTest, UnmanagedDevice) { MockDeviceManagementBackendFailRegister( DeviceManagementBackend::kErrorServiceManagementNotSupported)); EXPECT_FALSE(cache_->is_unmanaged()); - DeviceTokenFetcher fetcher(&service_, cache_.get(), ¬ifier_); - MockTokenAvailableObserver observer; - EXPECT_CALL(observer, OnDeviceTokenAvailable()).Times(0); - fetcher.AddObserver(&observer); - fetcher.FetchToken("fake_auth_token", "fake_device_id", - em::DeviceRegisterRequest::USER, - "fake_machine_id", "fake_machine_model"); + DeviceTokenFetcher fetcher(&service_, cache_.get(), data_store_.get(), + ¬ifier_); + EXPECT_CALL(observer_, OnDeviceTokenChanged()).Times(0); + FetchToken(&fetcher); loop_.RunAllPending(); - Mock::VerifyAndClearExpectations(&observer); - EXPECT_EQ("", fetcher.GetDeviceToken()); + Mock::VerifyAndClearExpectations(&observer_); + EXPECT_EQ("", data_store_->device_token()); EXPECT_TRUE(cache_->is_unmanaged()); - fetcher.RemoveObserver(&observer); } } // namespace policy diff --git a/chrome/browser/policy/logging_work_scheduler.cc b/chrome/browser/policy/logging_work_scheduler.cc index 8585ac0..a5181bb 100644 --- a/chrome/browser/policy/logging_work_scheduler.cc +++ b/chrome/browser/policy/logging_work_scheduler.cc @@ -142,8 +142,9 @@ void LoggingWorkScheduler::PostDelayedWork( } void LoggingWorkScheduler::CancelDelayedWork() { - DCHECK(callback_.get()); - callback_->Reset(); + if (!callback_.get()) return; + callback_->Reset(); // Erase the callback to the delayed work. + callback_.reset(NULL); // Erase the pointer to the callback. } } // namespace policy diff --git a/chrome/browser/policy/testing_cloud_policy_subsystem.cc b/chrome/browser/policy/testing_cloud_policy_subsystem.cc index 619accb..4bbd6c8 100644 --- a/chrome/browser/policy/testing_cloud_policy_subsystem.cc +++ b/chrome/browser/policy/testing_cloud_policy_subsystem.cc @@ -11,19 +11,20 @@ namespace policy { TestingCloudPolicySubsystem::TestingCloudPolicySubsystem( - CloudPolicyIdentityStrategy* identity_strategy, + CloudPolicyDataStore* data_store, CloudPolicyCacheBase* policy_cache, const std::string& device_management_url, EventLogger* logger) : CloudPolicySubsystem(), logger_(logger) { - Initialize(identity_strategy, policy_cache, device_management_url); + Initialize(data_store, policy_cache, device_management_url); } void TestingCloudPolicySubsystem::CreateDeviceTokenFetcher() { device_token_fetcher_.reset( new DeviceTokenFetcher(device_management_service_.get(), cloud_policy_cache_.get(), + data_store_, notifier_.get(), new LoggingWorkScheduler(logger_))); } @@ -33,7 +34,7 @@ void TestingCloudPolicySubsystem::CreateCloudPolicyController() { new CloudPolicyController(device_management_service_.get(), cloud_policy_cache_.get(), device_token_fetcher_.get(), - identity_strategy_, + data_store_, notifier_.get(), new LoggingWorkScheduler(logger_))); } diff --git a/chrome/browser/policy/testing_cloud_policy_subsystem.h b/chrome/browser/policy/testing_cloud_policy_subsystem.h index 4976817..fde7cda 100644 --- a/chrome/browser/policy/testing_cloud_policy_subsystem.h +++ b/chrome/browser/policy/testing_cloud_policy_subsystem.h @@ -10,6 +10,7 @@ namespace policy { +class CloudPolicyDataStore; class EventLogger; // A CloudPolicySubsystem for testing: it uses EventLogger to issue delayed @@ -17,7 +18,7 @@ class EventLogger; class TestingCloudPolicySubsystem : public CloudPolicySubsystem { public: // Takes ownership of |policy_cache|. - TestingCloudPolicySubsystem(CloudPolicyIdentityStrategy* identity_strategy, + TestingCloudPolicySubsystem(CloudPolicyDataStore* data, CloudPolicyCacheBase* policy_cache, const std::string& device_management_url, EventLogger* logger); diff --git a/chrome/browser/policy/user_policy_identity_strategy.cc b/chrome/browser/policy/user_policy_identity_strategy.cc deleted file mode 100644 index b0a20ff..0000000 --- a/chrome/browser/policy/user_policy_identity_strategy.cc +++ /dev/null @@ -1,107 +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/user_policy_identity_strategy.h" - -#include "chrome/browser/policy/proto/device_management_backend.pb.h" -#include "chrome/browser/policy/proto/device_management_constants.h" -#include "chrome/common/guid.h" - -namespace policy { - -namespace em = enterprise_management; - -UserPolicyIdentityStrategy::UserPolicyIdentityStrategy( - const std::string& user_name, - const FilePath& cache_file) - : cache_loaded_(false), - user_name_(user_name), - ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { - cache_ = new UserPolicyTokenCache(weak_ptr_factory_.GetWeakPtr(), cache_file); -} - -UserPolicyIdentityStrategy::~UserPolicyIdentityStrategy() {} - -void UserPolicyIdentityStrategy::LoadTokenCache() { - cache_->Load(); -} - -std::string UserPolicyIdentityStrategy::GetDeviceToken() { - return device_token_; -} - -std::string UserPolicyIdentityStrategy::GetDeviceID() { - return device_id_; -} - -std::string UserPolicyIdentityStrategy::GetMachineID() { - return std::string(); -} - -std::string UserPolicyIdentityStrategy::GetMachineModel() { - return std::string(); -} - -em::DeviceRegisterRequest_Type -UserPolicyIdentityStrategy::GetPolicyRegisterType() { - return em::DeviceRegisterRequest::USER; -} - -std::string UserPolicyIdentityStrategy::GetPolicyType() { - return kChromeUserPolicyType; -} - -bool UserPolicyIdentityStrategy::GetCredentials(std::string* username, - std::string* auth_token) { - *username = user_name_; - *auth_token = auth_token_; - - return !username->empty() && !auth_token->empty() && !device_id_.empty(); -} - -void UserPolicyIdentityStrategy::OnDeviceTokenAvailable( - const std::string& token) { - DCHECK(!device_id_.empty()); - device_token_ = token; - cache_->Store(device_token_, device_id_); - NotifyDeviceTokenChanged(); -} - -void UserPolicyIdentityStrategy::CheckAndTriggerFetch() { - if (!user_name_.empty() && !auth_token_.empty() && cache_loaded_) { - // For user tokens, there is no actual identifier. We generate a random - // identifier instead each time we ask for the token. - // This shouldn't be done before the cache is loaded, because there may - // already be a device id and matching device token stored there. - device_id_ = guid::GenerateGUID(); - NotifyAuthChanged(); - } -} - -void UserPolicyIdentityStrategy::SetAuthToken(const std::string& auth_token) { - auth_token_ = auth_token; - - // Request a new device management server token, but only in case we - // don't already have it. - if (device_token_.empty()) - CheckAndTriggerFetch(); -} - -void UserPolicyIdentityStrategy::OnTokenCacheLoaded( - const std::string& token, - const std::string& device_id) { - if (cache_loaded_) - return; - cache_loaded_ = true; - if (!token.empty() && !device_id.empty()) { - device_token_ = token; - device_id_ = device_id; - NotifyDeviceTokenChanged(); - } else { - CheckAndTriggerFetch(); - } -} - - -} // namespace policy diff --git a/chrome/browser/policy/user_policy_identity_strategy.h b/chrome/browser/policy/user_policy_identity_strategy.h deleted file mode 100644 index 05b9e8a..0000000 --- a/chrome/browser/policy/user_policy_identity_strategy.h +++ /dev/null @@ -1,88 +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. - -#ifndef CHROME_BROWSER_POLICY_USER_POLICY_IDENTITY_STRATEGY_H_ -#define CHROME_BROWSER_POLICY_USER_POLICY_IDENTITY_STRATEGY_H_ -#pragma once - -#include <string> - -#include "base/compiler_specific.h" -#include "base/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/cloud_policy_identity_strategy.h" -#include "chrome/browser/policy/user_policy_token_cache.h" - -namespace policy { - -class DeviceManagementBackend; - -// A token provider implementation that provides a user device token for the -// user corresponding to given credentials. -class UserPolicyIdentityStrategy : public CloudPolicyIdentityStrategy, - public UserPolicyTokenCache::Delegate { - public: - UserPolicyIdentityStrategy(const std::string& user_name, - const FilePath& token_cache_file); - virtual ~UserPolicyIdentityStrategy(); - - // Start loading the token cache. - void LoadTokenCache(); - - // Set a newly arriving auth_token and maybe trigger a fetch. - void SetAuthToken(const std::string& auth_token); - - // CloudPolicyIdentityStrategy implementation: - virtual std::string GetDeviceToken() OVERRIDE; - virtual std::string GetDeviceID() OVERRIDE; - virtual std::string GetMachineID() OVERRIDE; - virtual std::string GetMachineModel() OVERRIDE; - virtual em::DeviceRegisterRequest_Type GetPolicyRegisterType() OVERRIDE; - virtual std::string GetPolicyType() OVERRIDE; - virtual bool GetCredentials(std::string* username, - std::string* auth_token) OVERRIDE; - virtual void OnDeviceTokenAvailable(const std::string& token) OVERRIDE; - - private: - // Checks whether a new token should be fetched and if so, sends out a - // notification. - void CheckAndTriggerFetch(); - - // Gets the current user. - std::string GetCurrentUser(); - - // Called from the token cache when the token has been loaded. - virtual void OnTokenCacheLoaded(const std::string& token, - const std::string& device_id) OVERRIDE; - - // Keeps the on-disk copy of the token. - scoped_refptr<UserPolicyTokenCache> cache_; - - // false until cache_ reports being loaded for the first time, true - // afterwards. - bool cache_loaded_; - - // The device ID we use. - std::string device_id_; - - // Current device token. Empty if not available. - std::string device_token_; - - // Current auth token. Empty if not available. - std::string auth_token_; - - // Current user name. Empty if not available. This is set on creation and not - // changed afterwards. - std::string user_name_; - - // Allows to construct weak ptrs. - base::WeakPtrFactory<UserPolicyTokenCache::Delegate> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(UserPolicyIdentityStrategy); -}; - -} // namespace policy - -#endif // CHROME_BROWSER_POLICY_USER_POLICY_IDENTITY_STRATEGY_H_ diff --git a/chrome/browser/policy/user_policy_token_cache.cc b/chrome/browser/policy/user_policy_token_cache.cc index e2341d8..74e06bc 100644 --- a/chrome/browser/policy/user_policy_token_cache.cc +++ b/chrome/browser/policy/user_policy_token_cache.cc @@ -7,6 +7,7 @@ #include "base/file_util.h" #include "base/metrics/histogram.h" #include "chrome/browser/policy/enterprise_metrics.h" +#include "chrome/browser/policy/proto/device_management_local.pb.h" #include "content/browser/browser_thread.h" namespace { @@ -31,13 +32,13 @@ namespace policy { namespace em = enterprise_management; -UserPolicyTokenCache::Delegate::~Delegate() {} - UserPolicyTokenCache::UserPolicyTokenCache( - const base::WeakPtr<Delegate>& delegate, + const base::WeakPtr<CloudPolicyDataStore>& data_store, const FilePath& cache_file) - : delegate_(delegate), - cache_file_(cache_file) {} + : data_store_(data_store), + cache_file_(cache_file) { + data_store_->AddObserver(this); +} void UserPolicyTokenCache::Load() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); @@ -58,6 +59,8 @@ void UserPolicyTokenCache::Store(const std::string& token, } UserPolicyTokenCache::~UserPolicyTokenCache() { + if (data_store_) + data_store_->RemoveObserver(this); } void UserPolicyTokenCache::LoadOnFileThread() { @@ -89,8 +92,11 @@ void UserPolicyTokenCache::LoadOnFileThread() { void UserPolicyTokenCache::NotifyOnUIThread(const std::string& token, const std::string& device_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - if (delegate_.get()) - delegate_->OnTokenCacheLoaded(token, device_id); + if (data_store_) { + data_store_->set_device_id(device_id); + data_store_->SetDeviceToken(token, true); + data_store_->NotifyDeviceTokenChanged(); + } } void UserPolicyTokenCache::StoreOnFileThread(const std::string& token, @@ -124,4 +130,19 @@ void UserPolicyTokenCache::StoreOnFileThread(const std::string& token, SampleUMA(kMetricTokenStoreSucceeded); } +void UserPolicyTokenCache::OnDeviceTokenChanged() { + if (!data_store_->device_token().empty() && + !data_store_->device_id().empty()) { + // This will also happen after loading the cache. + Store(data_store_->device_token(), data_store_->device_id()); + } +} + +void UserPolicyTokenCache::OnCredentialsChanged() { +} + +void UserPolicyTokenCache::OnDataStoreGoingAway() { + data_store_->RemoveObserver(this); +} + } // namespace policy diff --git a/chrome/browser/policy/user_policy_token_cache.h b/chrome/browser/policy/user_policy_token_cache.h index e9ab99d..e7eeed5 100644 --- a/chrome/browser/policy/user_policy_token_cache.h +++ b/chrome/browser/policy/user_policy_token_cache.h @@ -12,23 +12,16 @@ #include "base/file_path.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/policy/proto/device_management_local.pb.h" +#include "chrome/browser/policy/cloud_policy_data_store.h" namespace policy { // Responsible for managing the on-disk token cache. class UserPolicyTokenCache - : public base::RefCountedThreadSafe<UserPolicyTokenCache> { + : public base::RefCountedThreadSafe<UserPolicyTokenCache>, + public CloudPolicyDataStore::Observer { public: - // Callback interface for reporting a successfull load. - class Delegate { - public: - virtual ~Delegate(); - virtual void OnTokenCacheLoaded(const std::string& token, - const std::string& device_id) = 0; - }; - - UserPolicyTokenCache(const base::WeakPtr<Delegate>& delegate, + UserPolicyTokenCache(const base::WeakPtr<CloudPolicyDataStore>& data_store, const FilePath& cache_file); // Starts loading the disk cache. After the load is finished, the result is @@ -38,9 +31,14 @@ class UserPolicyTokenCache // Stores credentials asynchronously to disk. void Store(const std::string& token, const std::string& device_id); + // CloudPolicyData::Observer implementation: + virtual void OnDeviceTokenChanged() OVERRIDE; + virtual void OnCredentialsChanged() OVERRIDE; + virtual void OnDataStoreGoingAway() OVERRIDE; + private: friend class base::RefCountedThreadSafe<UserPolicyTokenCache>; - ~UserPolicyTokenCache(); + virtual ~UserPolicyTokenCache(); void LoadOnFileThread(); void NotifyOnUIThread(const std::string& token, @@ -48,7 +46,7 @@ class UserPolicyTokenCache void StoreOnFileThread(const std::string& token, const std::string& device_id); - const base::WeakPtr<Delegate> delegate_; + const base::WeakPtr<CloudPolicyDataStore> data_store_; const FilePath cache_file_; DISALLOW_COPY_AND_ASSIGN(UserPolicyTokenCache); diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 8c72af5..4eb38c2 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -1579,8 +1579,8 @@ 'browser/policy/cloud_policy_cache_base.h', 'browser/policy/cloud_policy_controller.cc', 'browser/policy/cloud_policy_controller.h', - 'browser/policy/cloud_policy_identity_strategy.cc', - 'browser/policy/cloud_policy_identity_strategy.h', + 'browser/policy/cloud_policy_data_store.cc', + 'browser/policy/cloud_policy_data_store.h', 'browser/policy/cloud_policy_provider.cc', 'browser/policy/cloud_policy_provider.h', 'browser/policy/cloud_policy_provider_impl.cc', @@ -1611,8 +1611,6 @@ 'browser/policy/device_management_service.h', 'browser/policy/device_policy_cache.cc', 'browser/policy/device_policy_cache.h', - 'browser/policy/device_policy_identity_strategy.cc', - 'browser/policy/device_policy_identity_strategy.h', 'browser/policy/device_token_fetcher.cc', 'browser/policy/device_token_fetcher.h', 'browser/policy/dummy_cloud_policy_provider.cc', @@ -1639,8 +1637,6 @@ 'browser/policy/user_policy_cache.h', 'browser/policy/user_policy_disk_cache.cc', 'browser/policy/user_policy_disk_cache.h', - 'browser/policy/user_policy_identity_strategy.cc', - 'browser/policy/user_policy_identity_strategy.h', 'browser/policy/user_policy_token_cache.cc', 'browser/policy/user_policy_token_cache.h', # TODO(danno): Find a better way to include these files @@ -3695,8 +3691,6 @@ ['exclude', 'browser/policy/device_policy_cache.h'], ['exclude', 'browser/policy/enterprise_install_attributes.cc'], ['exclude', 'browser/policy/enterprise_install_attributes.h'], - ['exclude', 'browser/policy/device_policy_identity_strategy.cc'], - ['exclude', 'browser/policy/device_policy_identity_strategy.h'], ['exclude', 'browser/policy/proto/chrome_device_policy.pb.cc'], ['exclude', 'browser/policy/proto/chrome_device_policy.pb.h'], ['exclude', 'browser/renderer_host/offline_resource_handler.cc'], |