user_cloud_policy_manager_chromeos_unittest.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" 6 7#include "base/bind.h" 8#include "base/bind_helpers.h" 9#include "base/callback.h" 10#include "base/message_loop/message_loop.h" 11#include "base/prefs/pref_registry_simple.h" 12#include "base/prefs/testing_pref_service.h" 13#include "base/run_loop.h" 14#include "base/sequenced_task_runner.h" 15#include "base/strings/string_util.h" 16#include "base/strings/utf_string_conversions.h" 17#include "base/test/test_simple_task_runner.h" 18#include "chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h" 19#include "chrome/browser/chromeos/profiles/profile_helper.h" 20#include "chrome/browser/prefs/browser_prefs.h" 21#include "chrome/browser/prefs/pref_service_syncable.h" 22#include "chrome/browser/signin/fake_profile_oauth2_token_service.h" 23#include "chrome/browser/signin/fake_profile_oauth2_token_service_wrapper.h" 24#include "chrome/browser/signin/profile_oauth2_token_service.h" 25#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" 26#include "chrome/common/chrome_constants.h" 27#include "chrome/test/base/testing_browser_process.h" 28#include "chrome/test/base/testing_profile.h" 29#include "chrome/test/base/testing_profile_manager.h" 30#include "components/policy/core/common/cloud/cloud_external_data_manager.h" 31#include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h" 32#include "components/policy/core/common/cloud/mock_cloud_policy_store.h" 33#include "components/policy/core/common/cloud/mock_device_management_service.h" 34#include "components/policy/core/common/external_data_fetcher.h" 35#include "components/policy/core/common/mock_configuration_policy_provider.h" 36#include "components/policy/core/common/schema_registry.h" 37#include "content/public/test/test_browser_thread_bundle.h" 38#include "google_apis/gaia/gaia_auth_consumer.h" 39#include "google_apis/gaia/gaia_constants.h" 40#include "google_apis/gaia/gaia_urls.h" 41#include "net/url_request/test_url_fetcher_factory.h" 42#include "net/url_request/url_fetcher_delegate.h" 43#include "net/url_request/url_request_context_getter.h" 44#include "net/url_request/url_request_status.h" 45#include "policy/policy_constants.h" 46#include "policy/proto/device_management_backend.pb.h" 47#include "testing/gmock/include/gmock/gmock.h" 48#include "testing/gtest/include/gtest/gtest.h" 49 50namespace em = enterprise_management; 51 52using testing::AnyNumber; 53using testing::AtLeast; 54using testing::Mock; 55using testing::_; 56 57namespace policy { 58 59namespace { 60 61const char kOAuthTokenCookie[] = "oauth_token=1234"; 62 63const char kOAuth2TokenPairData[] = 64 "{" 65 " \"refresh_token\": \"1234\"," 66 " \"access_token\": \"5678\"," 67 " \"expires_in\": 3600" 68 "}"; 69 70const char kOAuth2AccessTokenData[] = 71 "{" 72 " \"access_token\": \"5678\"," 73 " \"expires_in\": 3600" 74 "}"; 75 76} // namespace 77 78class UserCloudPolicyManagerChromeOSTest : public testing::Test { 79 protected: 80 UserCloudPolicyManagerChromeOSTest() 81 : store_(NULL), 82 external_data_manager_(NULL), 83 task_runner_(new base::TestSimpleTaskRunner()), 84 profile_(NULL), 85 signin_profile_(NULL) {} 86 87 virtual void SetUp() OVERRIDE { 88 // The initialization path that blocks on the initial policy fetch requires 89 // a signin Profile to use its URLRequestContext. 90 profile_manager_.reset( 91 new TestingProfileManager(TestingBrowserProcess::GetGlobal())); 92 ASSERT_TRUE(profile_manager_->SetUp()); 93 TestingProfile::TestingFactories factories; 94 factories.push_back( 95 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(), 96 FakeProfileOAuth2TokenServiceWrapper::Build)); 97 profile_ = profile_manager_->CreateTestingProfile( 98 chrome::kInitialProfile, scoped_ptr<PrefServiceSyncable>(), 99 base::UTF8ToUTF16("testing_profile"), 0, std::string(), factories); 100 signin_profile_ = profile_manager_->CreateTestingProfile(kSigninProfile); 101 signin_profile_->ForceIncognito(true); 102 // Usually the signin Profile and the main Profile are separate, but since 103 // the signin Profile is an OTR Profile then for this test it suffices to 104 // attach it to the main Profile. 105 profile_->SetOffTheRecordProfile(scoped_ptr<Profile>(signin_profile_)); 106 signin_profile_->SetOriginalProfile(profile_); 107 ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile()); 108 109 chrome::RegisterLocalState(prefs_.registry()); 110 111 // Set up a policy map for testing. 112 policy_map_.Set("HomepageLocation", 113 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 114 base::Value::CreateStringValue("http://chromium.org"), 115 NULL); 116 expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) 117 .CopyFrom(policy_map_); 118 119 // Create fake policy blobs to deliver to the client. 120 em::DeviceRegisterResponse* register_response = 121 register_blob_.mutable_register_response(); 122 register_response->set_device_management_token("dmtoken123"); 123 124 em::CloudPolicySettings policy_proto; 125 policy_proto.mutable_homepagelocation()->set_value("http://chromium.org"); 126 ASSERT_TRUE( 127 policy_proto.SerializeToString(policy_data_.mutable_policy_value())); 128 policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType); 129 policy_data_.set_request_token("dmtoken123"); 130 policy_data_.set_device_id("id987"); 131 em::PolicyFetchResponse* policy_response = 132 policy_blob_.mutable_policy_response()->add_response(); 133 ASSERT_TRUE(policy_data_.SerializeToString( 134 policy_response->mutable_policy_data())); 135 136 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _)) 137 .Times(AnyNumber()); 138 } 139 140 virtual void TearDown() OVERRIDE { 141 if (token_forwarder_) 142 token_forwarder_->Shutdown(); 143 if (manager_) { 144 manager_->RemoveObserver(&observer_); 145 manager_->Shutdown(); 146 } 147 signin_profile_ = NULL; 148 profile_ = NULL; 149 profile_manager_->DeleteTestingProfile(kSigninProfile); 150 profile_manager_->DeleteTestingProfile(chrome::kInitialProfile); 151 } 152 153 void CreateManager(bool wait_for_fetch, int fetch_timeout) { 154 store_ = new MockCloudPolicyStore(); 155 external_data_manager_ = new MockCloudExternalDataManager; 156 external_data_manager_->SetPolicyStore(store_); 157 EXPECT_CALL(*store_, Load()); 158 manager_.reset(new UserCloudPolicyManagerChromeOS( 159 scoped_ptr<CloudPolicyStore>(store_), 160 scoped_ptr<CloudExternalDataManager>(external_data_manager_), 161 base::FilePath(), 162 wait_for_fetch, 163 base::TimeDelta::FromSeconds(fetch_timeout), 164 task_runner_, 165 task_runner_, 166 task_runner_)); 167 manager_->Init(&schema_registry_); 168 manager_->AddObserver(&observer_); 169 manager_->Connect(&prefs_, &device_management_service_, NULL, 170 USER_AFFILIATION_NONE); 171 Mock::VerifyAndClearExpectations(store_); 172 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 173 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 174 175 if (!wait_for_fetch) { 176 // Create the UserCloudPolicyTokenForwarder, which fetches the access 177 // token using the OAuth2PolicyFetcher and forwards it to the 178 // UserCloudPolicyManagerChromeOS. This service is automatically created 179 // for regular Profiles but not for testing Profiles. 180 ProfileOAuth2TokenService* token_service = 181 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); 182 ASSERT_TRUE(token_service); 183 token_forwarder_.reset( 184 new UserCloudPolicyTokenForwarder(manager_.get(), token_service)); 185 } 186 } 187 188 // Expects a pending URLFetcher for the |expected_url|, and returns it with 189 // prepared to deliver a response to its delegate. 190 net::TestURLFetcher* PrepareOAuthFetcher(const GURL& expected_url) { 191 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0); 192 EXPECT_TRUE(fetcher); 193 if (!fetcher) 194 return NULL; 195 EXPECT_TRUE(fetcher->delegate()); 196 EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(), 197 expected_url.spec(), 198 true)); 199 fetcher->set_url(fetcher->GetOriginalURL()); 200 fetcher->set_response_code(200); 201 fetcher->set_status(net::URLRequestStatus()); 202 return fetcher; 203 } 204 205 // Issues the OAuth2 tokens and returns the device management register job 206 // if the flow succeeded. 207 MockDeviceManagementJob* IssueOAuthToken(bool has_request_token) { 208 EXPECT_FALSE(manager_->core()->client()->is_registered()); 209 210 // Issuing this token triggers the callback of the OAuth2PolicyFetcher, 211 // which triggers the registration request. 212 MockDeviceManagementJob* register_request = NULL; 213 EXPECT_CALL(device_management_service_, 214 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _)) 215 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request)); 216 217 if (!has_request_token) { 218 GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); 219 net::TestURLFetcher* fetcher = NULL; 220 221 // Issue the oauth_token cookie first. 222 fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url()); 223 if (!fetcher) 224 return NULL; 225 net::ResponseCookies cookies; 226 cookies.push_back(kOAuthTokenCookie); 227 fetcher->set_cookies(cookies); 228 fetcher->delegate()->OnURLFetchComplete(fetcher); 229 230 // Issue the refresh token. 231 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url()); 232 if (!fetcher) 233 return NULL; 234 fetcher->SetResponseString(kOAuth2TokenPairData); 235 fetcher->delegate()->OnURLFetchComplete(fetcher); 236 237 // Issue the access token. 238 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url()); 239 if (!fetcher) 240 return NULL; 241 fetcher->SetResponseString(kOAuth2AccessTokenData); 242 fetcher->delegate()->OnURLFetchComplete(fetcher); 243 } else { 244 // Since the refresh token is available, OAuth2TokenService was used 245 // to request the access token and not UserCloudPolicyTokenForwarder. 246 // Issue the access token with the former. 247 FakeProfileOAuth2TokenService* token_service = 248 static_cast<FakeProfileOAuth2TokenService*>( 249 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)); 250 EXPECT_TRUE(token_service); 251 OAuth2TokenService::ScopeSet scopes; 252 scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth); 253 scopes.insert( 254 GaiaUrls::GetInstance()->oauth_wrap_bridge_user_info_scope()); 255 token_service->IssueTokenForScope( 256 scopes, "5678", 257 base::Time::Now() + base::TimeDelta::FromSeconds(3600)); 258 } 259 260 EXPECT_TRUE(register_request); 261 EXPECT_FALSE(manager_->core()->client()->is_registered()); 262 263 Mock::VerifyAndClearExpectations(&device_management_service_); 264 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _)) 265 .Times(AnyNumber()); 266 267 return register_request; 268 } 269 270 // Expects a policy fetch request to be issued after invoking |trigger_fetch|. 271 // This method replies to that fetch request and verifies that the manager 272 // handled the response. 273 void FetchPolicy(const base::Closure& trigger_fetch) { 274 MockDeviceManagementJob* policy_request = NULL; 275 EXPECT_CALL(device_management_service_, 276 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _)) 277 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request)); 278 trigger_fetch.Run(); 279 ASSERT_TRUE(policy_request); 280 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 281 EXPECT_TRUE(manager_->core()->client()->is_registered()); 282 283 Mock::VerifyAndClearExpectations(&device_management_service_); 284 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _)) 285 .Times(AnyNumber()); 286 287 // Send the initial policy back. This completes the initialization flow. 288 EXPECT_CALL(*store_, Store(_)); 289 policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_); 290 Mock::VerifyAndClearExpectations(store_); 291 292 // Notifying that the store is has cached the fetched policy completes the 293 // process, and initializes the manager. 294 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); 295 store_->policy_map_.CopyFrom(policy_map_); 296 store_->NotifyStoreLoaded(); 297 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 298 Mock::VerifyAndClearExpectations(&observer_); 299 EXPECT_TRUE(manager_->policies().Equals(expected_bundle_)); 300 } 301 302 // Required by the refresh scheduler that's created by the manager and 303 // for the cleanup of URLRequestContextGetter in the |signin_profile_|. 304 content::TestBrowserThreadBundle thread_bundle_; 305 306 // Convenience policy objects. 307 em::PolicyData policy_data_; 308 em::DeviceManagementResponse register_blob_; 309 em::DeviceManagementResponse policy_blob_; 310 PolicyMap policy_map_; 311 PolicyBundle expected_bundle_; 312 313 // Policy infrastructure. 314 net::TestURLFetcherFactory test_url_fetcher_factory_; 315 TestingPrefServiceSimple prefs_; 316 MockConfigurationPolicyObserver observer_; 317 MockDeviceManagementService device_management_service_; 318 MockCloudPolicyStore* store_; // Not owned. 319 MockCloudExternalDataManager* external_data_manager_; // Not owned. 320 scoped_refptr<base::TestSimpleTaskRunner> task_runner_; 321 SchemaRegistry schema_registry_; 322 scoped_ptr<UserCloudPolicyManagerChromeOS> manager_; 323 scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_; 324 325 // Required by ProfileHelper to get the signin Profile context. 326 scoped_ptr<TestingProfileManager> profile_manager_; 327 TestingProfile* profile_; 328 TestingProfile* signin_profile_; 329 330 static const char kSigninProfile[]; 331 332 private: 333 DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest); 334}; 335 336const char UserCloudPolicyManagerChromeOSTest::kSigninProfile[] = 337 "signin_profile"; 338 339TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) { 340 // Tests the initialization of a manager whose Profile is waiting for the 341 // initial fetch, when the policy cache is empty. 342 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000)); 343 344 // Initialize the CloudPolicyService without any stored data. 345 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 346 store_->NotifyStoreLoaded(); 347 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 348 EXPECT_FALSE(manager_->core()->client()->is_registered()); 349 350 // This starts the OAuth2 policy token fetcher using the signin Profile. 351 // The manager will then issue the registration request. 352 MockDeviceManagementJob* register_request = IssueOAuthToken(false); 353 ASSERT_TRUE(register_request); 354 355 // Reply with a valid registration response. This triggers the initial policy 356 // fetch. 357 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse, 358 base::Unretained(register_request), 359 DM_STATUS_SUCCESS, register_blob_)); 360} 361 362TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) { 363 // Tests the initialization of a manager whose Profile is waiting for the 364 // initial fetch, when a previously cached policy and DMToken already exist. 365 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000)); 366 367 // Set the initially cached data and initialize the CloudPolicyService. 368 // The initial policy fetch is issued using the cached DMToken. 369 store_->policy_.reset(new em::PolicyData(policy_data_)); 370 FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded, 371 base::Unretained(store_))); 372} 373 374TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) { 375 // Tests the initialization of a manager whose Profile is waiting for the 376 // initial fetch, when the initial store load fails. 377 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000)); 378 379 // Initialize the CloudPolicyService without any stored data. 380 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 381 store_->NotifyStoreError(); 382 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 383 EXPECT_FALSE(manager_->core()->client()->is_registered()); 384 385 // This starts the OAuth2 policy token fetcher using the signin Profile. 386 // The manager will then issue the registration request. 387 MockDeviceManagementJob* register_request = IssueOAuthToken(false); 388 ASSERT_TRUE(register_request); 389 390 // Reply with a valid registration response. This triggers the initial policy 391 // fetch. 392 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse, 393 base::Unretained(register_request), 394 DM_STATUS_SUCCESS, register_blob_)); 395} 396 397TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) { 398 // Tests the initialization of a manager whose Profile is waiting for the 399 // initial fetch, when the OAuth2 token fetch fails. 400 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000)); 401 402 // Initialize the CloudPolicyService without any stored data. 403 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 404 store_->NotifyStoreLoaded(); 405 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 406 EXPECT_FALSE(manager_->core()->client()->is_registered()); 407 408 // This starts the OAuth2 policy token fetcher using the signin Profile. 409 // The manager will initialize with no policy after the token fetcher fails. 410 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); 411 412 // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This 413 // data will make it fail immediately. 414 net::TestURLFetcher* fetcher = PrepareOAuthFetcher( 415 GaiaUrls::GetInstance()->client_login_to_oauth2_url()); 416 ASSERT_TRUE(fetcher); 417 fetcher->set_response_code(400); 418 fetcher->SetResponseString("Error=BadAuthentication"); 419 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 420 fetcher->delegate()->OnURLFetchComplete(fetcher); 421 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 422 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); 423 Mock::VerifyAndClearExpectations(&observer_); 424} 425 426TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) { 427 // Tests the initialization of a manager whose Profile is waiting for the 428 // initial fetch, when the device management registration fails. 429 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000)); 430 431 // Initialize the CloudPolicyService without any stored data. 432 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 433 store_->NotifyStoreError(); 434 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 435 EXPECT_FALSE(manager_->core()->client()->is_registered()); 436 437 // This starts the OAuth2 policy token fetcher using the signin Profile. 438 // The manager will then issue the registration request. 439 MockDeviceManagementJob* register_request = IssueOAuthToken(false); 440 ASSERT_TRUE(register_request); 441 442 // Now make it fail. 443 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 444 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); 445 register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE, 446 em::DeviceManagementResponse()); 447 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 448 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); 449 Mock::VerifyAndClearExpectations(&observer_); 450} 451 452TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) { 453 // Tests the initialization of a manager whose Profile is waiting for the 454 // initial fetch, when the policy fetch request fails. 455 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000)); 456 457 // Initialize the CloudPolicyService without any stored data. 458 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 459 store_->NotifyStoreLoaded(); 460 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 461 EXPECT_FALSE(manager_->core()->client()->is_registered()); 462 463 // This starts the OAuth2 policy token fetcher using the signin Profile. 464 // The manager will then issue the registration request. 465 MockDeviceManagementJob* register_request = IssueOAuthToken(false); 466 ASSERT_TRUE(register_request); 467 468 // Reply with a valid registration response. This triggers the initial policy 469 // fetch. 470 MockDeviceManagementJob* policy_request = NULL; 471 EXPECT_CALL(device_management_service_, 472 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _)) 473 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request)); 474 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_); 475 Mock::VerifyAndClearExpectations(&device_management_service_); 476 ASSERT_TRUE(policy_request); 477 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 478 EXPECT_TRUE(manager_->core()->client()->is_registered()); 479 480 // Make the policy fetch fail. The observer gets 2 notifications: one from the 481 // RefreshPolicies callback, and another from the OnClientError callback. 482 // A single notification suffices for this edge case, but this behavior is 483 // also correct and makes the implementation simpler. 484 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1)); 485 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 486 policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE, 487 em::DeviceManagementResponse()); 488 Mock::VerifyAndClearExpectations(&observer_); 489 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 490 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); 491} 492 493TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) { 494 // The blocking fetch should be abandoned after the timeout. 495 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 0)); 496 497 // Initialize the CloudPolicyService without any stored data. 498 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 499 store_->NotifyStoreLoaded(); 500 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 501 EXPECT_FALSE(manager_->core()->client()->is_registered()); 502 503 // Running the message loop should trigger the timeout. 504 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1)); 505 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 506 base::RunLoop().RunUntilIdle(); 507 Mock::VerifyAndClearExpectations(&observer_); 508 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 509 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies())); 510} 511 512 513TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) { 514 // Tests the first policy fetch request by a Profile that isn't managed. 515 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000)); 516 517 // Initialize the CloudPolicyService without any stored data. Since the 518 // manager is not waiting for the initial fetch, it will become initialized 519 // once the store is ready. 520 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 521 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 522 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); 523 store_->NotifyStoreLoaded(); 524 Mock::VerifyAndClearExpectations(&observer_); 525 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 526 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 527 EXPECT_FALSE(manager_->core()->client()->is_registered()); 528 529 // The manager is waiting for the refresh token, and hasn't started any 530 // fetchers. 531 EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0)); 532 533 // Set a fake refresh token at the OAuth2TokenService. 534 FakeProfileOAuth2TokenService* token_service = 535 static_cast<FakeProfileOAuth2TokenService*>( 536 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)); 537 ASSERT_TRUE(token_service); 538 const std::string account_id = token_service->GetPrimaryAccountId(); 539 EXPECT_FALSE(token_service->RefreshTokenIsAvailable(account_id)); 540 token_service->UpdateCredentials(account_id, "refresh_token"); 541 EXPECT_TRUE(token_service->RefreshTokenIsAvailable(account_id)); 542 543 // That should have notified the manager, which now issues the request for the 544 // policy oauth token. 545 MockDeviceManagementJob* register_request = IssueOAuthToken(true); 546 ASSERT_TRUE(register_request); 547 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_); 548 549 // The refresh scheduler takes care of the initial fetch for unmanaged users. 550 // Running the task runner issues the initial fetch. 551 FetchPolicy( 552 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_)); 553} 554 555TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) { 556 // Tests a non-blocking initial policy fetch for a Profile that already has 557 // a cached DMToken. 558 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000)); 559 560 // Set the initially cached data and initialize the CloudPolicyService. 561 // The initial policy fetch is issued using the cached DMToken. 562 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete()); 563 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 564 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())); 565 store_->policy_.reset(new em::PolicyData(policy_data_)); 566 store_->NotifyStoreLoaded(); 567 Mock::VerifyAndClearExpectations(&observer_); 568 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete()); 569 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); 570 EXPECT_TRUE(manager_->core()->client()->is_registered()); 571 572 // The refresh scheduler takes care of the initial fetch for unmanaged users. 573 // Running the task runner issues the initial fetch. 574 FetchPolicy( 575 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_)); 576} 577 578} // namespace policy 579