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