Upstream version 6.35.121.0
[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.h"
26 #include "chrome/browser/signin/signin_manager_factory.h"
27 #include "chrome/common/chrome_constants.h"
28 #include "chrome/test/base/testing_browser_process.h"
29 #include "chrome/test/base/testing_profile.h"
30 #include "chrome/test/base/testing_profile_manager.h"
31 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
32 #include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h"
33 #include "components/policy/core/common/cloud/mock_cloud_policy_store.h"
34 #include "components/policy/core/common/cloud/mock_device_management_service.h"
35 #include "components/policy/core/common/external_data_fetcher.h"
36 #include "components/policy/core/common/mock_configuration_policy_provider.h"
37 #include "components/policy/core/common/schema_registry.h"
38 #include "components/signin/core/browser/profile_oauth2_token_service.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("HomepageLocation",
115                     POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
116                     new base::StringValue("http://chromium.org"),
117                     NULL);
118     expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
119         .CopyFrom(policy_map_);
120
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");
125
126     em::CloudPolicySettings policy_proto;
127     policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
128     ASSERT_TRUE(
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()));
137
138     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
139         .Times(AnyNumber());
140   }
141
142   virtual void TearDown() OVERRIDE {
143     if (token_forwarder_)
144       token_forwarder_->Shutdown();
145     if (manager_) {
146       manager_->RemoveObserver(&observer_);
147       manager_->Shutdown();
148     }
149     signin_profile_ = NULL;
150     profile_ = NULL;
151     profile_manager_->DeleteTestingProfile(kSigninProfile);
152     profile_manager_->DeleteTestingProfile(chrome::kInitialProfile);
153   }
154
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_),
163         base::FilePath(),
164         wait_for_fetch,
165         base::TimeDelta::FromSeconds(fetch_timeout),
166         task_runner_,
167         task_runner_,
168         task_runner_));
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());
176
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,
190                                             signin_manager));
191     }
192   }
193
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);
199     if (!fetcher)
200       return NULL;
201     EXPECT_TRUE(fetcher->delegate());
202     EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(),
203                                 expected_url.spec(),
204                                 true));
205     fetcher->set_url(fetcher->GetOriginalURL());
206     fetcher->set_response_code(200);
207     fetcher->set_status(net::URLRequestStatus());
208     return fetcher;
209   }
210
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());
215
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(&register_request));
222
223     if (!has_request_token) {
224       GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
225       net::TestURLFetcher* fetcher = NULL;
226
227       // Issue the oauth_token cookie first.
228       fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url());
229       if (!fetcher)
230         return NULL;
231       net::ResponseCookies cookies;
232       cookies.push_back(kOAuthTokenCookie);
233       fetcher->set_cookies(cookies);
234       fetcher->delegate()->OnURLFetchComplete(fetcher);
235
236       // Issue the refresh token.
237       fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
238       if (!fetcher)
239         return NULL;
240       fetcher->SetResponseString(kOAuth2TokenPairData);
241       fetcher->delegate()->OnURLFetchComplete(fetcher);
242
243       // Issue the access token.
244       fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
245       if (!fetcher)
246         return NULL;
247       fetcher->SetResponseString(kOAuth2AccessTokenData);
248       fetcher->delegate()->OnURLFetchComplete(fetcher);
249     } else {
250       // Since the refresh token is available, OAuth2TokenService was used
251       // to request the access token and not UserCloudPolicyTokenForwarder.
252       // Issue the access token with the former.
253       FakeProfileOAuth2TokenService* token_service =
254         static_cast<FakeProfileOAuth2TokenService*>(
255             ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
256       EXPECT_TRUE(token_service);
257       OAuth2TokenService::ScopeSet scopes;
258       scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth);
259       scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
260       token_service->IssueTokenForScope(
261           scopes, "5678",
262           base::Time::Now() + base::TimeDelta::FromSeconds(3600));
263     }
264
265     EXPECT_TRUE(register_request);
266     EXPECT_FALSE(manager_->core()->client()->is_registered());
267
268     Mock::VerifyAndClearExpectations(&device_management_service_);
269     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
270         .Times(AnyNumber());
271
272     return register_request;
273   }
274
275   // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
276   // This method replies to that fetch request and verifies that the manager
277   // handled the response.
278   void FetchPolicy(const base::Closure& trigger_fetch) {
279     MockDeviceManagementJob* policy_request = NULL;
280     EXPECT_CALL(device_management_service_,
281                 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
282         .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
283     trigger_fetch.Run();
284     ASSERT_TRUE(policy_request);
285     EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
286     EXPECT_TRUE(manager_->core()->client()->is_registered());
287
288     Mock::VerifyAndClearExpectations(&device_management_service_);
289     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
290         .Times(AnyNumber());
291
292     // Send the initial policy back. This completes the initialization flow.
293     EXPECT_CALL(*store_, Store(_));
294     policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
295     Mock::VerifyAndClearExpectations(store_);
296
297     // Notifying that the store is has cached the fetched policy completes the
298     // process, and initializes the manager.
299     EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
300     store_->policy_map_.CopyFrom(policy_map_);
301     store_->NotifyStoreLoaded();
302     EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
303     Mock::VerifyAndClearExpectations(&observer_);
304     EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
305   }
306
307   // Required by the refresh scheduler that's created by the manager and
308   // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
309   content::TestBrowserThreadBundle thread_bundle_;
310
311   // Convenience policy objects.
312   em::PolicyData policy_data_;
313   em::DeviceManagementResponse register_blob_;
314   em::DeviceManagementResponse policy_blob_;
315   PolicyMap policy_map_;
316   PolicyBundle expected_bundle_;
317
318   // Policy infrastructure.
319   net::TestURLFetcherFactory test_url_fetcher_factory_;
320   TestingPrefServiceSimple prefs_;
321   MockConfigurationPolicyObserver observer_;
322   MockDeviceManagementService device_management_service_;
323   MockCloudPolicyStore* store_;  // Not owned.
324   MockCloudExternalDataManager* external_data_manager_;  // Not owned.
325   scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
326   SchemaRegistry schema_registry_;
327   scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
328   scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
329
330   // Required by ProfileHelper to get the signin Profile context.
331   scoped_ptr<TestingProfileManager> profile_manager_;
332   TestingProfile* profile_;
333   TestingProfile* signin_profile_;
334
335   static const char kSigninProfile[];
336
337  private:
338   DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
339 };
340
341 const char UserCloudPolicyManagerChromeOSTest::kSigninProfile[] =
342     "signin_profile";
343
344 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
345   // Tests the initialization of a manager whose Profile is waiting for the
346   // initial fetch, when the policy cache is empty.
347   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
348
349   // Initialize the CloudPolicyService without any stored data.
350   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
351   store_->NotifyStoreLoaded();
352   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
353   EXPECT_FALSE(manager_->core()->client()->is_registered());
354
355   // This starts the OAuth2 policy token fetcher using the signin Profile.
356   // The manager will then issue the registration request.
357   MockDeviceManagementJob* register_request = IssueOAuthToken(false);
358   ASSERT_TRUE(register_request);
359
360   // Reply with a valid registration response. This triggers the initial policy
361   // fetch.
362   FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
363                          base::Unretained(register_request),
364                          DM_STATUS_SUCCESS, register_blob_));
365 }
366
367 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
368   // Tests the initialization of a manager whose Profile is waiting for the
369   // initial fetch, when a previously cached policy and DMToken already exist.
370   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
371
372   // Set the initially cached data and initialize the CloudPolicyService.
373   // The initial policy fetch is issued using the cached DMToken.
374   store_->policy_.reset(new em::PolicyData(policy_data_));
375   FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
376                          base::Unretained(store_)));
377 }
378
379 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
380   // Tests the initialization of a manager whose Profile is waiting for the
381   // initial fetch, when the initial store load fails.
382   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
383
384   // Initialize the CloudPolicyService without any stored data.
385   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
386   store_->NotifyStoreError();
387   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
388   EXPECT_FALSE(manager_->core()->client()->is_registered());
389
390   // This starts the OAuth2 policy token fetcher using the signin Profile.
391   // The manager will then issue the registration request.
392   MockDeviceManagementJob* register_request = IssueOAuthToken(false);
393   ASSERT_TRUE(register_request);
394
395   // Reply with a valid registration response. This triggers the initial policy
396   // fetch.
397   FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
398                          base::Unretained(register_request),
399                          DM_STATUS_SUCCESS, register_blob_));
400 }
401
402 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
403   // Tests the initialization of a manager whose Profile is waiting for the
404   // initial fetch, when the OAuth2 token fetch fails.
405   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
406
407   // Initialize the CloudPolicyService without any stored data.
408   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
409   store_->NotifyStoreLoaded();
410   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
411   EXPECT_FALSE(manager_->core()->client()->is_registered());
412
413   // This starts the OAuth2 policy token fetcher using the signin Profile.
414   // The manager will initialize with no policy after the token fetcher fails.
415   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
416
417   // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
418   // data will make it fail immediately.
419   net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
420       GaiaUrls::GetInstance()->client_login_to_oauth2_url());
421   ASSERT_TRUE(fetcher);
422   fetcher->set_response_code(400);
423   fetcher->SetResponseString("Error=BadAuthentication");
424   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
425   fetcher->delegate()->OnURLFetchComplete(fetcher);
426   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
427   EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
428   Mock::VerifyAndClearExpectations(&observer_);
429 }
430
431 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
432   // Tests the initialization of a manager whose Profile is waiting for the
433   // initial fetch, when the device management registration fails.
434   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
435
436   // Initialize the CloudPolicyService without any stored data.
437   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
438   store_->NotifyStoreError();
439   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
440   EXPECT_FALSE(manager_->core()->client()->is_registered());
441
442   // This starts the OAuth2 policy token fetcher using the signin Profile.
443   // The manager will then issue the registration request.
444   MockDeviceManagementJob* register_request = IssueOAuthToken(false);
445   ASSERT_TRUE(register_request);
446
447   // Now make it fail.
448   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
449   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
450   register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
451                                  em::DeviceManagementResponse());
452   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
453   EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
454   Mock::VerifyAndClearExpectations(&observer_);
455 }
456
457 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
458   // Tests the initialization of a manager whose Profile is waiting for the
459   // initial fetch, when the policy fetch request fails.
460   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
461
462   // Initialize the CloudPolicyService without any stored data.
463   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
464   store_->NotifyStoreLoaded();
465   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
466   EXPECT_FALSE(manager_->core()->client()->is_registered());
467
468   // This starts the OAuth2 policy token fetcher using the signin Profile.
469   // The manager will then issue the registration request.
470   MockDeviceManagementJob* register_request = IssueOAuthToken(false);
471   ASSERT_TRUE(register_request);
472
473   // Reply with a valid registration response. This triggers the initial policy
474   // fetch.
475   MockDeviceManagementJob* policy_request = NULL;
476   EXPECT_CALL(device_management_service_,
477               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
478       .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
479   register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
480   Mock::VerifyAndClearExpectations(&device_management_service_);
481   ASSERT_TRUE(policy_request);
482   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
483   EXPECT_TRUE(manager_->core()->client()->is_registered());
484
485   // Make the policy fetch fail. The observer gets 2 notifications: one from the
486   // RefreshPolicies callback, and another from the OnClientError callback.
487   // A single notification suffices for this edge case, but this behavior is
488   // also correct and makes the implementation simpler.
489   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
490   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
491   policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
492                                em::DeviceManagementResponse());
493   Mock::VerifyAndClearExpectations(&observer_);
494   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
495   EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
496 }
497
498 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) {
499   // The blocking fetch should be abandoned after the timeout.
500   ASSERT_NO_FATAL_FAILURE(CreateManager(true, 0));
501
502   // Initialize the CloudPolicyService without any stored data.
503   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
504   store_->NotifyStoreLoaded();
505   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
506   EXPECT_FALSE(manager_->core()->client()->is_registered());
507
508   // Running the message loop should trigger the timeout.
509   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
510   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
511   base::RunLoop().RunUntilIdle();
512   Mock::VerifyAndClearExpectations(&observer_);
513   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
514   EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
515 }
516
517
518 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
519   // Tests the first policy fetch request by a Profile that isn't managed.
520   ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
521
522   // Initialize the CloudPolicyService without any stored data. Since the
523   // manager is not waiting for the initial fetch, it will become initialized
524   // once the store is ready.
525   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
526   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
527   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
528   store_->NotifyStoreLoaded();
529   Mock::VerifyAndClearExpectations(&observer_);
530   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
531   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
532   EXPECT_FALSE(manager_->core()->client()->is_registered());
533
534   // The manager is waiting for the refresh token, and hasn't started any
535   // fetchers.
536   EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
537
538   // Set a fake refresh token at the OAuth2TokenService.
539   FakeProfileOAuth2TokenService* token_service =
540     static_cast<FakeProfileOAuth2TokenService*>(
541         ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
542   ASSERT_TRUE(token_service);
543   SigninManagerBase* signin_manager =
544       SigninManagerFactory::GetForProfile(profile_);
545   ASSERT_TRUE(signin_manager);
546   const std::string& account_id = signin_manager->GetAuthenticatedAccountId();
547   EXPECT_FALSE(token_service->RefreshTokenIsAvailable(account_id));
548   token_service->UpdateCredentials(account_id, "refresh_token");
549   EXPECT_TRUE(token_service->RefreshTokenIsAvailable(account_id));
550
551   // That should have notified the manager, which now issues the request for the
552   // policy oauth token.
553   MockDeviceManagementJob* register_request = IssueOAuthToken(true);
554   ASSERT_TRUE(register_request);
555   register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
556
557   // The refresh scheduler takes care of the initial fetch for unmanaged users.
558   // Running the task runner issues the initial fetch.
559   FetchPolicy(
560       base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
561 }
562
563 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
564   // Tests a non-blocking initial policy fetch for a Profile that already has
565   // a cached DMToken.
566   ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
567
568   // Set the initially cached data and initialize the CloudPolicyService.
569   // The initial policy fetch is issued using the cached DMToken.
570   EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
571   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
572   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
573   store_->policy_.reset(new em::PolicyData(policy_data_));
574   store_->NotifyStoreLoaded();
575   Mock::VerifyAndClearExpectations(&observer_);
576   EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
577   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
578   EXPECT_TRUE(manager_->core()->client()->is_registered());
579
580   // The refresh scheduler takes care of the initial fetch for unmanaged users.
581   // Running the task runner issues the initial fetch.
582   FetchPolicy(
583       base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
584 }
585
586 }  // namespace policy