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.
5 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.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_builder.h"
24 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
25 #include "chrome/browser/signin/signin_manager_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 "components/signin/core/browser/profile_oauth2_token_service.h"
38 #include "components/signin/core/browser/signin_manager.h"
39 #include "content/public/test/test_browser_thread_bundle.h"
40 #include "google_apis/gaia/gaia_auth_consumer.h"
41 #include "google_apis/gaia/gaia_constants.h"
42 #include "google_apis/gaia/gaia_urls.h"
43 #include "net/url_request/test_url_fetcher_factory.h"
44 #include "net/url_request/url_fetcher_delegate.h"
45 #include "net/url_request/url_request_context_getter.h"
46 #include "net/url_request/url_request_status.h"
47 #include "policy/policy_constants.h"
48 #include "policy/proto/device_management_backend.pb.h"
49 #include "testing/gmock/include/gmock/gmock.h"
50 #include "testing/gtest/include/gtest/gtest.h"
52 namespace em = enterprise_management;
54 using testing::AnyNumber;
55 using testing::AtLeast;
61 const char kOAuthCodeCookie[] = "oauth_code=1234; Secure; HttpOnly";
63 const char kOAuth2TokenPairData[] =
65 " \"refresh_token\": \"1234\","
66 " \"access_token\": \"5678\","
67 " \"expires_in\": 3600"
70 const char kOAuth2AccessTokenData[] =
72 " \"access_token\": \"5678\","
73 " \"expires_in\": 3600"
76 class UserCloudPolicyManagerChromeOSTest : public testing::Test {
78 UserCloudPolicyManagerChromeOSTest()
80 external_data_manager_(NULL),
81 task_runner_(new base::TestSimpleTaskRunner()),
83 signin_profile_(NULL) {}
85 virtual void SetUp() OVERRIDE {
86 // The initialization path that blocks on the initial policy fetch requires
87 // a signin Profile to use its URLRequestContext.
88 profile_manager_.reset(
89 new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
90 ASSERT_TRUE(profile_manager_->SetUp());
91 TestingProfile::TestingFactories factories;
93 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
94 BuildFakeProfileOAuth2TokenService));
95 profile_ = profile_manager_->CreateTestingProfile(
96 chrome::kInitialProfile, scoped_ptr<PrefServiceSyncable>(),
97 base::UTF8ToUTF16("testing_profile"), 0, std::string(), factories);
98 signin_profile_ = profile_manager_->CreateTestingProfile(kSigninProfile);
99 signin_profile_->ForceIncognito(true);
100 // Usually the signin Profile and the main Profile are separate, but since
101 // the signin Profile is an OTR Profile then for this test it suffices to
102 // attach it to the main Profile.
103 profile_->SetOffTheRecordProfile(scoped_ptr<Profile>(signin_profile_));
104 signin_profile_->SetOriginalProfile(profile_);
105 ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile());
107 chrome::RegisterLocalState(prefs_.registry());
109 // Set up a policy map for testing.
110 policy_map_.Set(key::kHomepageLocation,
111 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
112 new base::StringValue("http://chromium.org"),
114 policy_map_.Set(key::kChromeOsMultiProfileUserBehavior,
115 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
116 new base::StringValue("primary-only"),
118 expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
119 .CopyFrom(policy_map_);
121 // Create fake policy blobs to deliver to the client.
122 em::DeviceRegisterResponse* register_response =
123 register_blob_.mutable_register_response();
124 register_response->set_device_management_token("dmtoken123");
126 em::CloudPolicySettings policy_proto;
127 policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
129 policy_proto.SerializeToString(policy_data_.mutable_policy_value()));
130 policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType);
131 policy_data_.set_request_token("dmtoken123");
132 policy_data_.set_device_id("id987");
133 em::PolicyFetchResponse* policy_response =
134 policy_blob_.mutable_policy_response()->add_response();
135 ASSERT_TRUE(policy_data_.SerializeToString(
136 policy_response->mutable_policy_data()));
138 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
142 virtual void TearDown() OVERRIDE {
143 if (token_forwarder_)
144 token_forwarder_->Shutdown();
146 manager_->RemoveObserver(&observer_);
147 manager_->Shutdown();
149 signin_profile_ = NULL;
151 profile_manager_->DeleteTestingProfile(kSigninProfile);
152 profile_manager_->DeleteTestingProfile(chrome::kInitialProfile);
155 void CreateManager(bool wait_for_fetch, int fetch_timeout) {
156 store_ = new MockCloudPolicyStore();
157 external_data_manager_ = new MockCloudExternalDataManager;
158 external_data_manager_->SetPolicyStore(store_);
159 EXPECT_CALL(*store_, Load());
160 manager_.reset(new UserCloudPolicyManagerChromeOS(
161 scoped_ptr<CloudPolicyStore>(store_),
162 scoped_ptr<CloudExternalDataManager>(external_data_manager_),
165 base::TimeDelta::FromSeconds(fetch_timeout),
169 manager_->Init(&schema_registry_);
170 manager_->AddObserver(&observer_);
171 manager_->Connect(&prefs_, &device_management_service_, NULL,
172 USER_AFFILIATION_NONE);
173 Mock::VerifyAndClearExpectations(store_);
174 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
175 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
177 if (!wait_for_fetch) {
178 // Create the UserCloudPolicyTokenForwarder, which fetches the access
179 // token using the OAuth2PolicyFetcher and forwards it to the
180 // UserCloudPolicyManagerChromeOS. This service is automatically created
181 // for regular Profiles but not for testing Profiles.
182 ProfileOAuth2TokenService* token_service =
183 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
184 ASSERT_TRUE(token_service);
185 SigninManagerBase* signin_manager =
186 SigninManagerFactory::GetForProfile(profile_);
187 ASSERT_TRUE(signin_manager);
188 token_forwarder_.reset(
189 new UserCloudPolicyTokenForwarder(manager_.get(), token_service,
194 // Expects a pending URLFetcher for the |expected_url|, and returns it with
195 // prepared to deliver a response to its delegate.
196 net::TestURLFetcher* PrepareOAuthFetcher(const GURL& expected_url) {
197 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0);
198 EXPECT_TRUE(fetcher);
201 EXPECT_TRUE(fetcher->delegate());
202 EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(),
205 fetcher->set_url(fetcher->GetOriginalURL());
206 fetcher->set_response_code(200);
207 fetcher->set_status(net::URLRequestStatus());
211 // Issues the OAuth2 tokens and returns the device management register job
212 // if the flow succeeded.
213 MockDeviceManagementJob* IssueOAuthToken(bool has_request_token) {
214 EXPECT_FALSE(manager_->core()->client()->is_registered());
216 // Issuing this token triggers the callback of the OAuth2PolicyFetcher,
217 // which triggers the registration request.
218 MockDeviceManagementJob* register_request = NULL;
219 EXPECT_CALL(device_management_service_,
220 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
221 .WillOnce(device_management_service_.CreateAsyncJob(®ister_request));
223 if (!has_request_token) {
224 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
225 net::TestURLFetcher* fetcher = NULL;
227 // Issue the oauth_token cookie first.
228 fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url());
231 net::ResponseCookies cookies;
232 cookies.push_back(kOAuthCodeCookie);
234 fetcher->set_cookies(cookies);
235 fetcher->delegate()->OnURLFetchComplete(fetcher);
237 // Issue the refresh token.
238 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
241 fetcher->SetResponseString(kOAuth2TokenPairData);
242 fetcher->delegate()->OnURLFetchComplete(fetcher);
244 // Issue the access token.
245 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
248 fetcher->SetResponseString(kOAuth2AccessTokenData);
249 fetcher->delegate()->OnURLFetchComplete(fetcher);
251 // Since the refresh token is available, OAuth2TokenService was used
252 // to request the access token and not UserCloudPolicyTokenForwarder.
253 // Issue the access token with the former.
254 FakeProfileOAuth2TokenService* token_service =
255 static_cast<FakeProfileOAuth2TokenService*>(
256 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
257 EXPECT_TRUE(token_service);
258 OAuth2TokenService::ScopeSet scopes;
259 scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth);
260 scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
261 token_service->IssueTokenForScope(
263 base::Time::Now() + base::TimeDelta::FromSeconds(3600));
266 EXPECT_TRUE(register_request);
267 EXPECT_FALSE(manager_->core()->client()->is_registered());
269 Mock::VerifyAndClearExpectations(&device_management_service_);
270 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
273 return register_request;
276 // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
277 // This method replies to that fetch request and verifies that the manager
278 // handled the response.
279 void FetchPolicy(const base::Closure& trigger_fetch) {
280 MockDeviceManagementJob* policy_request = NULL;
281 EXPECT_CALL(device_management_service_,
282 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
283 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
285 ASSERT_TRUE(policy_request);
286 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
287 EXPECT_TRUE(manager_->core()->client()->is_registered());
289 Mock::VerifyAndClearExpectations(&device_management_service_);
290 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
293 // Send the initial policy back. This completes the initialization flow.
294 EXPECT_CALL(*store_, Store(_));
295 policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
296 Mock::VerifyAndClearExpectations(store_);
298 // Notifying that the store is has cached the fetched policy completes the
299 // process, and initializes the manager.
300 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
301 store_->policy_map_.CopyFrom(policy_map_);
302 store_->NotifyStoreLoaded();
303 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
304 Mock::VerifyAndClearExpectations(&observer_);
305 EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
308 // Required by the refresh scheduler that's created by the manager and
309 // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
310 content::TestBrowserThreadBundle thread_bundle_;
312 // Convenience policy objects.
313 em::PolicyData policy_data_;
314 em::DeviceManagementResponse register_blob_;
315 em::DeviceManagementResponse policy_blob_;
316 PolicyMap policy_map_;
317 PolicyBundle expected_bundle_;
319 // Policy infrastructure.
320 net::TestURLFetcherFactory test_url_fetcher_factory_;
321 TestingPrefServiceSimple prefs_;
322 MockConfigurationPolicyObserver observer_;
323 MockDeviceManagementService device_management_service_;
324 MockCloudPolicyStore* store_; // Not owned.
325 MockCloudExternalDataManager* external_data_manager_; // Not owned.
326 scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
327 SchemaRegistry schema_registry_;
328 scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
329 scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
331 // Required by ProfileHelper to get the signin Profile context.
332 scoped_ptr<TestingProfileManager> profile_manager_;
333 TestingProfile* profile_;
334 TestingProfile* signin_profile_;
336 static const char kSigninProfile[];
339 DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
342 const char UserCloudPolicyManagerChromeOSTest::kSigninProfile[] =
345 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
346 // Tests the initialization of a manager whose Profile is waiting for the
347 // initial fetch, when the policy cache is empty.
348 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
350 // Initialize the CloudPolicyService without any stored data.
351 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
352 store_->NotifyStoreLoaded();
353 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
354 EXPECT_FALSE(manager_->core()->client()->is_registered());
356 // This starts the OAuth2 policy token fetcher using the signin Profile.
357 // The manager will then issue the registration request.
358 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
359 ASSERT_TRUE(register_request);
361 // Reply with a valid registration response. This triggers the initial policy
363 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
364 base::Unretained(register_request),
365 DM_STATUS_SUCCESS, register_blob_));
368 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
369 // Tests the initialization of a manager whose Profile is waiting for the
370 // initial fetch, when a previously cached policy and DMToken already exist.
371 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
373 // Set the initially cached data and initialize the CloudPolicyService.
374 // The initial policy fetch is issued using the cached DMToken.
375 store_->policy_.reset(new em::PolicyData(policy_data_));
376 FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
377 base::Unretained(store_)));
380 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
381 // Tests the initialization of a manager whose Profile is waiting for the
382 // initial fetch, when the initial store load fails.
383 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
385 // Initialize the CloudPolicyService without any stored data.
386 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
387 store_->NotifyStoreError();
388 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
389 EXPECT_FALSE(manager_->core()->client()->is_registered());
391 // This starts the OAuth2 policy token fetcher using the signin Profile.
392 // The manager will then issue the registration request.
393 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
394 ASSERT_TRUE(register_request);
396 // Reply with a valid registration response. This triggers the initial policy
398 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
399 base::Unretained(register_request),
400 DM_STATUS_SUCCESS, register_blob_));
403 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
404 // Tests the initialization of a manager whose Profile is waiting for the
405 // initial fetch, when the OAuth2 token fetch fails.
406 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
408 // Initialize the CloudPolicyService without any stored data.
409 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
410 store_->NotifyStoreLoaded();
411 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
412 EXPECT_FALSE(manager_->core()->client()->is_registered());
414 // This starts the OAuth2 policy token fetcher using the signin Profile.
415 // The manager will initialize with no policy after the token fetcher fails.
416 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
418 // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
419 // data will make it fail immediately.
420 net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
421 GaiaUrls::GetInstance()->client_login_to_oauth2_url());
422 ASSERT_TRUE(fetcher);
423 fetcher->set_response_code(400);
424 fetcher->SetResponseString("Error=BadAuthentication");
425 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
426 fetcher->delegate()->OnURLFetchComplete(fetcher);
427 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
428 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
429 Mock::VerifyAndClearExpectations(&observer_);
432 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
433 // Tests the initialization of a manager whose Profile is waiting for the
434 // initial fetch, when the device management registration fails.
435 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
437 // Initialize the CloudPolicyService without any stored data.
438 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
439 store_->NotifyStoreError();
440 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
441 EXPECT_FALSE(manager_->core()->client()->is_registered());
443 // This starts the OAuth2 policy token fetcher using the signin Profile.
444 // The manager will then issue the registration request.
445 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
446 ASSERT_TRUE(register_request);
449 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
450 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
451 register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
452 em::DeviceManagementResponse());
453 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
454 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
455 Mock::VerifyAndClearExpectations(&observer_);
458 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
459 // Tests the initialization of a manager whose Profile is waiting for the
460 // initial fetch, when the policy fetch request fails.
461 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
463 // Initialize the CloudPolicyService without any stored data.
464 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
465 store_->NotifyStoreLoaded();
466 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
467 EXPECT_FALSE(manager_->core()->client()->is_registered());
469 // This starts the OAuth2 policy token fetcher using the signin Profile.
470 // The manager will then issue the registration request.
471 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
472 ASSERT_TRUE(register_request);
474 // Reply with a valid registration response. This triggers the initial policy
476 MockDeviceManagementJob* policy_request = NULL;
477 EXPECT_CALL(device_management_service_,
478 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
479 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
480 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
481 Mock::VerifyAndClearExpectations(&device_management_service_);
482 ASSERT_TRUE(policy_request);
483 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
484 EXPECT_TRUE(manager_->core()->client()->is_registered());
486 // Make the policy fetch fail. The observer gets 2 notifications: one from the
487 // RefreshPolicies callback, and another from the OnClientError callback.
488 // A single notification suffices for this edge case, but this behavior is
489 // also correct and makes the implementation simpler.
490 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
491 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
492 policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
493 em::DeviceManagementResponse());
494 Mock::VerifyAndClearExpectations(&observer_);
495 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
496 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
499 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) {
500 // The blocking fetch should be abandoned after the timeout.
501 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 0));
503 // Initialize the CloudPolicyService without any stored data.
504 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
505 store_->NotifyStoreLoaded();
506 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
507 EXPECT_FALSE(manager_->core()->client()->is_registered());
509 // Running the message loop should trigger the timeout.
510 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
511 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
512 base::RunLoop().RunUntilIdle();
513 Mock::VerifyAndClearExpectations(&observer_);
514 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
515 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
519 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
520 // Tests the first policy fetch request by a Profile that isn't managed.
521 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
523 // Initialize the CloudPolicyService without any stored data. Since the
524 // manager is not waiting for the initial fetch, it will become initialized
525 // once the store is ready.
526 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
527 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
528 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
529 store_->NotifyStoreLoaded();
530 Mock::VerifyAndClearExpectations(&observer_);
531 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
532 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
533 EXPECT_FALSE(manager_->core()->client()->is_registered());
535 // The manager is waiting for the refresh token, and hasn't started any
537 EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
539 // Set a fake refresh token at the OAuth2TokenService.
540 FakeProfileOAuth2TokenService* token_service =
541 static_cast<FakeProfileOAuth2TokenService*>(
542 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
543 ASSERT_TRUE(token_service);
544 SigninManagerBase* signin_manager =
545 SigninManagerFactory::GetForProfile(profile_);
546 ASSERT_TRUE(signin_manager);
547 const std::string& account_id = signin_manager->GetAuthenticatedAccountId();
548 EXPECT_FALSE(token_service->RefreshTokenIsAvailable(account_id));
549 token_service->UpdateCredentials(account_id, "refresh_token");
550 EXPECT_TRUE(token_service->RefreshTokenIsAvailable(account_id));
552 // That should have notified the manager, which now issues the request for the
553 // policy oauth token.
554 MockDeviceManagementJob* register_request = IssueOAuthToken(true);
555 ASSERT_TRUE(register_request);
556 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
558 // The refresh scheduler takes care of the initial fetch for unmanaged users.
559 // Running the task runner issues the initial fetch.
561 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
564 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
565 // Tests a non-blocking initial policy fetch for a Profile that already has
567 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
569 // Set the initially cached data and initialize the CloudPolicyService.
570 // The initial policy fetch is issued using the cached DMToken.
571 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
572 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
573 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
574 store_->policy_.reset(new em::PolicyData(policy_data_));
575 store_->NotifyStoreLoaded();
576 Mock::VerifyAndClearExpectations(&observer_);
577 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
578 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
579 EXPECT_TRUE(manager_->core()->client()->is_registered());
581 // The refresh scheduler takes care of the initial fetch for unmanaged users.
582 // Running the task runner issues the initial fetch.
584 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
587 } // namespace policy