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