Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / user_cloud_policy_manager_chromeos_unittest.cc
blob8790d09f7bfa2b208c714c3d3f4ac6a60e0ba78a
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"
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/login/users/scoped_user_manager_enabler.h"
19 #include "chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h"
20 #include "chrome/browser/chromeos/profiles/profile_helper.h"
21 #include "chrome/browser/prefs/browser_prefs.h"
22 #include "chrome/browser/prefs/pref_service_syncable.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/fake_profile_oauth2_token_service.h"
38 #include "components/signin/core/browser/profile_oauth2_token_service.h"
39 #include "components/signin/core/browser/signin_manager.h"
40 #include "components/user_manager/fake_user_manager.h"
41 #include "content/public/test/test_browser_thread_bundle.h"
42 #include "google_apis/gaia/gaia_auth_consumer.h"
43 #include "google_apis/gaia/gaia_constants.h"
44 #include "google_apis/gaia/gaia_urls.h"
45 #include "net/url_request/test_url_fetcher_factory.h"
46 #include "net/url_request/url_fetcher_delegate.h"
47 #include "net/url_request/url_request_context_getter.h"
48 #include "net/url_request/url_request_status.h"
49 #include "policy/policy_constants.h"
50 #include "policy/proto/device_management_backend.pb.h"
51 #include "testing/gmock/include/gmock/gmock.h"
52 #include "testing/gtest/include/gtest/gtest.h"
54 namespace em = enterprise_management;
56 using testing::AnyNumber;
57 using testing::AtLeast;
58 using testing::Mock;
59 using testing::_;
61 namespace policy {
63 const char kOAuthCodeCookie[] = "oauth_code=1234; Secure; HttpOnly";
65 const char kOAuth2TokenPairData[] =
66 "{"
67 " \"refresh_token\": \"1234\","
68 " \"access_token\": \"5678\","
69 " \"expires_in\": 3600"
70 "}";
72 const char kOAuth2AccessTokenData[] =
73 "{"
74 " \"access_token\": \"5678\","
75 " \"expires_in\": 3600"
76 "}";
78 class 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 user_manager_(new user_manager::FakeUserManager()),
87 user_manager_enabler_(user_manager_) {}
89 void SetUp() override {
90 // The initialization path that blocks on the initial policy fetch requires
91 // a signin Profile to use its URLRequestContext.
92 profile_manager_.reset(
93 new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
94 ASSERT_TRUE(profile_manager_->SetUp());
95 TestingProfile::TestingFactories factories;
96 factories.push_back(
97 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
98 BuildFakeProfileOAuth2TokenService));
99 profile_ = profile_manager_->CreateTestingProfile(
100 chrome::kInitialProfile,
101 scoped_ptr<PrefServiceSyncable>(),
102 base::UTF8ToUTF16(""),
104 std::string(),
105 factories);
106 // Usually the signin Profile and the main Profile are separate, but since
107 // the signin Profile is an OTR Profile then for this test it suffices to
108 // attach it to the main Profile.
109 signin_profile_ = TestingProfile::Builder().BuildIncognito(profile_);
110 ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile());
112 chrome::RegisterLocalState(prefs_.registry());
114 // Set up a policy map for testing.
115 policy_map_.Set(key::kHomepageLocation,
116 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
117 new base::StringValue("http://chromium.org"),
118 NULL);
119 policy_map_.Set(key::kChromeOsMultiProfileUserBehavior,
120 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
121 new base::StringValue("primary-only"),
122 NULL);
123 policy_map_.Set(key::kEasyUnlockAllowed,
124 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
125 new base::FundamentalValue(false),
126 NULL);
127 policy_map_.Set(key::kCaptivePortalAuthenticationIgnoresProxy,
128 POLICY_LEVEL_MANDATORY,
129 POLICY_SCOPE_USER,
130 new base::FundamentalValue(false),
131 NULL);
132 expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
133 .CopyFrom(policy_map_);
135 // Create fake policy blobs to deliver to the client.
136 em::DeviceRegisterResponse* register_response =
137 register_blob_.mutable_register_response();
138 register_response->set_device_management_token("dmtoken123");
140 em::CloudPolicySettings policy_proto;
141 policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
142 ASSERT_TRUE(
143 policy_proto.SerializeToString(policy_data_.mutable_policy_value()));
144 policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType);
145 policy_data_.set_request_token("dmtoken123");
146 policy_data_.set_device_id("id987");
147 em::PolicyFetchResponse* policy_response =
148 policy_blob_.mutable_policy_response()->add_response();
149 ASSERT_TRUE(policy_data_.SerializeToString(
150 policy_response->mutable_policy_data()));
152 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
153 .Times(AnyNumber());
156 void TearDown() override {
157 if (token_forwarder_)
158 token_forwarder_->Shutdown();
159 if (manager_) {
160 manager_->RemoveObserver(&observer_);
161 manager_->Shutdown();
163 signin_profile_ = NULL;
164 profile_ = NULL;
165 profile_manager_->DeleteTestingProfile(chrome::kInitialProfile);
168 void CreateManager(bool wait_for_fetch, int fetch_timeout) {
169 store_ = new MockCloudPolicyStore();
170 external_data_manager_ = new MockCloudExternalDataManager;
171 external_data_manager_->SetPolicyStore(store_);
172 EXPECT_CALL(*store_, Load());
173 manager_.reset(new UserCloudPolicyManagerChromeOS(
174 scoped_ptr<CloudPolicyStore>(store_),
175 scoped_ptr<CloudExternalDataManager>(external_data_manager_),
176 base::FilePath(),
177 wait_for_fetch,
178 base::TimeDelta::FromSeconds(fetch_timeout),
179 task_runner_,
180 task_runner_,
181 task_runner_));
182 manager_->Init(&schema_registry_);
183 manager_->AddObserver(&observer_);
184 manager_->Connect(&prefs_, &device_management_service_, NULL);
185 Mock::VerifyAndClearExpectations(store_);
186 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
187 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
189 if (!wait_for_fetch) {
190 // Create the UserCloudPolicyTokenForwarder, which fetches the access
191 // token using the OAuth2PolicyFetcher and forwards it to the
192 // UserCloudPolicyManagerChromeOS. This service is automatically created
193 // for regular Profiles but not for testing Profiles.
194 ProfileOAuth2TokenService* token_service =
195 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
196 ASSERT_TRUE(token_service);
197 SigninManagerBase* signin_manager =
198 SigninManagerFactory::GetForProfile(profile_);
199 ASSERT_TRUE(signin_manager);
200 token_forwarder_.reset(
201 new UserCloudPolicyTokenForwarder(manager_.get(), token_service,
202 signin_manager));
206 // Expects a pending URLFetcher for the |expected_url|, and returns it with
207 // prepared to deliver a response to its delegate.
208 net::TestURLFetcher* PrepareOAuthFetcher(const GURL& expected_url) {
209 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0);
210 EXPECT_TRUE(fetcher);
211 if (!fetcher)
212 return NULL;
213 EXPECT_TRUE(fetcher->delegate());
214 EXPECT_TRUE(base::StartsWith(fetcher->GetOriginalURL().spec(),
215 expected_url.spec(),
216 base::CompareCase::SENSITIVE));
217 fetcher->set_url(fetcher->GetOriginalURL());
218 fetcher->set_response_code(200);
219 fetcher->set_status(net::URLRequestStatus());
220 return fetcher;
223 // Issues the OAuth2 tokens and returns the device management register job
224 // if the flow succeeded.
225 MockDeviceManagementJob* IssueOAuthToken(bool has_request_token) {
226 EXPECT_FALSE(manager_->core()->client()->is_registered());
228 // Issuing this token triggers the callback of the OAuth2PolicyFetcher,
229 // which triggers the registration request.
230 MockDeviceManagementJob* register_request = NULL;
231 EXPECT_CALL(device_management_service_,
232 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
233 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
235 if (!has_request_token) {
236 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
237 net::TestURLFetcher* fetcher = NULL;
239 // Issue the oauth_token cookie first.
240 fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url());
241 if (!fetcher)
242 return NULL;
243 net::ResponseCookies cookies;
244 cookies.push_back(kOAuthCodeCookie);
246 fetcher->set_cookies(cookies);
247 fetcher->delegate()->OnURLFetchComplete(fetcher);
249 // Issue the refresh token.
250 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
251 if (!fetcher)
252 return NULL;
253 fetcher->SetResponseString(kOAuth2TokenPairData);
254 fetcher->delegate()->OnURLFetchComplete(fetcher);
256 // Issue the access token.
257 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
258 if (!fetcher)
259 return NULL;
260 fetcher->SetResponseString(kOAuth2AccessTokenData);
261 fetcher->delegate()->OnURLFetchComplete(fetcher);
262 } else {
263 // Since the refresh token is available, OAuth2TokenService was used
264 // to request the access token and not UserCloudPolicyTokenForwarder.
265 // Issue the access token with the former.
266 FakeProfileOAuth2TokenService* token_service =
267 static_cast<FakeProfileOAuth2TokenService*>(
268 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
269 EXPECT_TRUE(token_service);
270 OAuth2TokenService::ScopeSet scopes;
271 scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth);
272 scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
273 token_service->IssueTokenForScope(
274 scopes, "5678",
275 base::Time::Now() + base::TimeDelta::FromSeconds(3600));
278 EXPECT_TRUE(register_request);
279 EXPECT_FALSE(manager_->core()->client()->is_registered());
281 Mock::VerifyAndClearExpectations(&device_management_service_);
282 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
283 .Times(AnyNumber());
285 return register_request;
288 // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
289 // This method replies to that fetch request and verifies that the manager
290 // handled the response.
291 void FetchPolicy(const base::Closure& trigger_fetch) {
292 MockDeviceManagementJob* policy_request = NULL;
293 EXPECT_CALL(device_management_service_,
294 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
295 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
296 trigger_fetch.Run();
297 ASSERT_TRUE(policy_request);
298 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
299 EXPECT_TRUE(manager_->core()->client()->is_registered());
301 Mock::VerifyAndClearExpectations(&device_management_service_);
302 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _))
303 .Times(AnyNumber());
305 // Send the initial policy back. This completes the initialization flow.
306 EXPECT_CALL(*store_, Store(_));
307 policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
308 Mock::VerifyAndClearExpectations(store_);
310 // Notifying that the store is has cached the fetched policy completes the
311 // process, and initializes the manager.
312 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
313 store_->policy_map_.CopyFrom(policy_map_);
314 store_->NotifyStoreLoaded();
315 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
316 Mock::VerifyAndClearExpectations(&observer_);
317 EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
320 // Required by the refresh scheduler that's created by the manager and
321 // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
322 content::TestBrowserThreadBundle thread_bundle_;
324 // Convenience policy objects.
325 em::PolicyData policy_data_;
326 em::DeviceManagementResponse register_blob_;
327 em::DeviceManagementResponse policy_blob_;
328 PolicyMap policy_map_;
329 PolicyBundle expected_bundle_;
331 // Policy infrastructure.
332 net::TestURLFetcherFactory test_url_fetcher_factory_;
333 TestingPrefServiceSimple prefs_;
334 MockConfigurationPolicyObserver observer_;
335 MockDeviceManagementService device_management_service_;
336 MockCloudPolicyStore* store_; // Not owned.
337 MockCloudExternalDataManager* external_data_manager_; // Not owned.
338 scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
339 SchemaRegistry schema_registry_;
340 scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
341 scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
343 // Required by ProfileHelper to get the signin Profile context.
344 scoped_ptr<TestingProfileManager> profile_manager_;
345 TestingProfile* profile_;
346 TestingProfile* signin_profile_;
348 user_manager::FakeUserManager* user_manager_;
349 chromeos::ScopedUserManagerEnabler user_manager_enabler_;
351 private:
352 DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
355 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
356 // Tests the initialization of a manager whose Profile is waiting for the
357 // initial fetch, when the policy cache is empty.
358 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
360 // Initialize the CloudPolicyService without any stored data.
361 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
362 store_->NotifyStoreLoaded();
363 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
364 EXPECT_FALSE(manager_->core()->client()->is_registered());
366 // This starts the OAuth2 policy token fetcher using the signin Profile.
367 // The manager will then issue the registration request.
368 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
369 ASSERT_TRUE(register_request);
371 // Reply with a valid registration response. This triggers the initial policy
372 // fetch.
373 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
374 base::Unretained(register_request),
375 DM_STATUS_SUCCESS, register_blob_));
378 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
379 // Tests the initialization of a manager whose Profile is waiting for the
380 // initial fetch, when a previously cached policy and DMToken already exist.
381 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
383 // Set the initially cached data and initialize the CloudPolicyService.
384 // The initial policy fetch is issued using the cached DMToken.
385 store_->policy_.reset(new em::PolicyData(policy_data_));
386 FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
387 base::Unretained(store_)));
390 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
391 // Tests the initialization of a manager whose Profile is waiting for the
392 // initial fetch, when the initial store load fails.
393 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
395 // Initialize the CloudPolicyService without any stored data.
396 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
397 store_->NotifyStoreError();
398 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
399 EXPECT_FALSE(manager_->core()->client()->is_registered());
401 // This starts the OAuth2 policy token fetcher using the signin Profile.
402 // The manager will then issue the registration request.
403 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
404 ASSERT_TRUE(register_request);
406 // Reply with a valid registration response. This triggers the initial policy
407 // fetch.
408 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
409 base::Unretained(register_request),
410 DM_STATUS_SUCCESS, register_blob_));
413 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
414 // Tests the initialization of a manager whose Profile is waiting for the
415 // initial fetch, when the OAuth2 token fetch fails.
416 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
418 // Initialize the CloudPolicyService without any stored data.
419 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
420 store_->NotifyStoreLoaded();
421 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
422 EXPECT_FALSE(manager_->core()->client()->is_registered());
424 // This starts the OAuth2 policy token fetcher using the signin Profile.
425 // The manager will initialize with no policy after the token fetcher fails.
426 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
428 // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
429 // data will make it fail immediately.
430 net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
431 GaiaUrls::GetInstance()->client_login_to_oauth2_url());
432 ASSERT_TRUE(fetcher);
433 fetcher->set_response_code(400);
434 fetcher->SetResponseString("Error=BadAuthentication");
435 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
436 fetcher->delegate()->OnURLFetchComplete(fetcher);
437 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
438 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
439 Mock::VerifyAndClearExpectations(&observer_);
442 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
443 // Tests the initialization of a manager whose Profile is waiting for the
444 // initial fetch, when the device management registration fails.
445 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
447 // Initialize the CloudPolicyService without any stored data.
448 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
449 store_->NotifyStoreError();
450 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
451 EXPECT_FALSE(manager_->core()->client()->is_registered());
453 // This starts the OAuth2 policy token fetcher using the signin Profile.
454 // The manager will then issue the registration request.
455 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
456 ASSERT_TRUE(register_request);
458 // Now make it fail.
459 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
460 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
461 register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
462 em::DeviceManagementResponse());
463 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
464 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
465 Mock::VerifyAndClearExpectations(&observer_);
468 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
469 // Tests the initialization of a manager whose Profile is waiting for the
470 // initial fetch, when the policy fetch request fails.
471 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
473 // Initialize the CloudPolicyService without any stored data.
474 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
475 store_->NotifyStoreLoaded();
476 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
477 EXPECT_FALSE(manager_->core()->client()->is_registered());
479 // This starts the OAuth2 policy token fetcher using the signin Profile.
480 // The manager will then issue the registration request.
481 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
482 ASSERT_TRUE(register_request);
484 // Reply with a valid registration response. This triggers the initial policy
485 // fetch.
486 MockDeviceManagementJob* policy_request = NULL;
487 EXPECT_CALL(device_management_service_,
488 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
489 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
490 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
491 Mock::VerifyAndClearExpectations(&device_management_service_);
492 ASSERT_TRUE(policy_request);
493 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
494 EXPECT_TRUE(manager_->core()->client()->is_registered());
496 // Make the policy fetch fail. The observer gets 2 notifications: one from the
497 // RefreshPolicies callback, and another from the OnClientError callback.
498 // A single notification suffices for this edge case, but this behavior is
499 // also correct and makes the implementation simpler.
500 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
501 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
502 policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
503 em::DeviceManagementResponse());
504 Mock::VerifyAndClearExpectations(&observer_);
505 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
506 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
509 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) {
510 // The blocking fetch should be abandoned after the timeout.
511 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 0));
513 // Initialize the CloudPolicyService without any stored data.
514 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
515 store_->NotifyStoreLoaded();
516 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
517 EXPECT_FALSE(manager_->core()->client()->is_registered());
519 // Running the message loop should trigger the timeout.
520 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
521 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
522 base::RunLoop().RunUntilIdle();
523 Mock::VerifyAndClearExpectations(&observer_);
524 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
525 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
529 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
530 // Tests the first policy fetch request by a Profile that isn't managed.
531 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
533 // Initialize the CloudPolicyService without any stored data. Since the
534 // manager is not waiting for the initial fetch, it will become initialized
535 // once the store is ready.
536 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
537 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
538 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
539 store_->NotifyStoreLoaded();
540 Mock::VerifyAndClearExpectations(&observer_);
541 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
542 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
543 EXPECT_FALSE(manager_->core()->client()->is_registered());
545 // The manager is waiting for the refresh token, and hasn't started any
546 // fetchers.
547 EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
549 // Set a fake refresh token at the OAuth2TokenService.
550 FakeProfileOAuth2TokenService* token_service =
551 static_cast<FakeProfileOAuth2TokenService*>(
552 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
553 ASSERT_TRUE(token_service);
554 SigninManagerBase* signin_manager =
555 SigninManagerFactory::GetForProfile(profile_);
556 ASSERT_TRUE(signin_manager);
557 const std::string& account_id = signin_manager->GetAuthenticatedAccountId();
558 EXPECT_FALSE(token_service->RefreshTokenIsAvailable(account_id));
559 token_service->UpdateCredentials(account_id, "refresh_token");
560 EXPECT_TRUE(token_service->RefreshTokenIsAvailable(account_id));
562 // That should have notified the manager, which now issues the request for the
563 // policy oauth token.
564 MockDeviceManagementJob* register_request = IssueOAuthToken(true);
565 ASSERT_TRUE(register_request);
566 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
568 // The refresh scheduler takes care of the initial fetch for unmanaged users.
569 // Running the task runner issues the initial fetch.
570 FetchPolicy(
571 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
574 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
575 // Tests a non-blocking initial policy fetch for a Profile that already has
576 // a cached DMToken.
577 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
579 // Set the initially cached data and initialize the CloudPolicyService.
580 // The initial policy fetch is issued using the cached DMToken.
581 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
582 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
583 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
584 store_->policy_.reset(new em::PolicyData(policy_data_));
585 store_->NotifyStoreLoaded();
586 Mock::VerifyAndClearExpectations(&observer_);
587 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
588 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
589 EXPECT_TRUE(manager_->core()->client()->is_registered());
591 // The refresh scheduler takes care of the initial fetch for unmanaged users.
592 // Running the task runner issues the initial fetch.
593 FetchPolicy(
594 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
597 } // namespace policy