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