user_cloud_policy_manager_chromeos_unittest.cc revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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
52namespace em = enterprise_management;
53
54using testing::AnyNumber;
55using testing::AtLeast;
56using testing::Mock;
57using testing::_;
58
59namespace policy {
60
61const char kOAuthCodeCookie[] = "oauth_code=1234; Secure; HttpOnly";
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
76class UserCloudPolicyManagerChromeOSTest : public testing::Test {
77 protected:
78  UserCloudPolicyManagerChromeOSTest()
79      : store_(NULL),
80        external_data_manager_(NULL),
81        task_runner_(new base::TestSimpleTaskRunner()),
82        profile_(NULL),
83        signin_profile_(NULL) {}
84
85  virtual void SetUp() OVERRIDE {
86    // The initialization path that blocks on the initial policy fetch requires
87    // a signin Profile to use its URLRequestContext.
88    profile_manager_.reset(
89        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
90    ASSERT_TRUE(profile_manager_->SetUp());
91    TestingProfile::TestingFactories factories;
92    factories.push_back(
93        std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
94                       BuildFakeProfileOAuth2TokenService));
95    profile_ = profile_manager_->CreateTestingProfile(
96        chrome::kInitialProfile, scoped_ptr<PrefServiceSyncable>(),
97        base::UTF8ToUTF16("testing_profile"), 0, std::string(), factories);
98    signin_profile_ = profile_manager_->CreateTestingProfile(kSigninProfile);
99    signin_profile_->ForceIncognito(true);
100    // Usually the signin Profile and the main Profile are separate, but since
101    // the signin Profile is an OTR Profile then for this test it suffices to
102    // attach it to the main Profile.
103    profile_->SetOffTheRecordProfile(scoped_ptr<Profile>(signin_profile_));
104    signin_profile_->SetOriginalProfile(profile_);
105    ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile());
106
107    chrome::RegisterLocalState(prefs_.registry());
108
109    // Set up a policy map for testing.
110    policy_map_.Set(key::kHomepageLocation,
111                    POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
112                    new base::StringValue("http://chromium.org"),
113                    NULL);
114    policy_map_.Set(key::kChromeOsMultiProfileUserBehavior,
115                    POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
116                    new base::StringValue("not-allowed"),
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(kOAuthCodeCookie);
233
234      fetcher->set_cookies(cookies);
235      fetcher->delegate()->OnURLFetchComplete(fetcher);
236
237      // Issue the refresh token.
238      fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
239      if (!fetcher)
240        return NULL;
241      fetcher->SetResponseString(kOAuth2TokenPairData);
242      fetcher->delegate()->OnURLFetchComplete(fetcher);
243
244      // Issue the access token.
245      fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
246      if (!fetcher)
247        return NULL;
248      fetcher->SetResponseString(kOAuth2AccessTokenData);
249      fetcher->delegate()->OnURLFetchComplete(fetcher);
250    } else {
251      // Since the refresh token is available, OAuth2TokenService was used
252      // to request the access token and not UserCloudPolicyTokenForwarder.
253      // Issue the access token with the former.
254      FakeProfileOAuth2TokenService* token_service =
255        static_cast<FakeProfileOAuth2TokenService*>(
256            ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
257      EXPECT_TRUE(token_service);
258      OAuth2TokenService::ScopeSet scopes;
259      scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth);
260      scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
261      token_service->IssueTokenForScope(
262          scopes, "5678",
263          base::Time::Now() + base::TimeDelta::FromSeconds(3600));
264    }
265
266    EXPECT_TRUE(register_request);
267    EXPECT_FALSE(manager_->core()->client()->is_registered());
268
269    Mock::VerifyAndClearExpectations(&device_management_service_);
270    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
271        .Times(AnyNumber());
272
273    return register_request;
274  }
275
276  // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
277  // This method replies to that fetch request and verifies that the manager
278  // handled the response.
279  void FetchPolicy(const base::Closure& trigger_fetch) {
280    MockDeviceManagementJob* policy_request = NULL;
281    EXPECT_CALL(device_management_service_,
282                CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
283        .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
284    trigger_fetch.Run();
285    ASSERT_TRUE(policy_request);
286    EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
287    EXPECT_TRUE(manager_->core()->client()->is_registered());
288
289    Mock::VerifyAndClearExpectations(&device_management_service_);
290    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
291        .Times(AnyNumber());
292
293    // Send the initial policy back. This completes the initialization flow.
294    EXPECT_CALL(*store_, Store(_));
295    policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
296    Mock::VerifyAndClearExpectations(store_);
297
298    // Notifying that the store is has cached the fetched policy completes the
299    // process, and initializes the manager.
300    EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
301    store_->policy_map_.CopyFrom(policy_map_);
302    store_->NotifyStoreLoaded();
303    EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
304    Mock::VerifyAndClearExpectations(&observer_);
305    EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
306  }
307
308  // Required by the refresh scheduler that's created by the manager and
309  // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
310  content::TestBrowserThreadBundle thread_bundle_;
311
312  // Convenience policy objects.
313  em::PolicyData policy_data_;
314  em::DeviceManagementResponse register_blob_;
315  em::DeviceManagementResponse policy_blob_;
316  PolicyMap policy_map_;
317  PolicyBundle expected_bundle_;
318
319  // Policy infrastructure.
320  net::TestURLFetcherFactory test_url_fetcher_factory_;
321  TestingPrefServiceSimple prefs_;
322  MockConfigurationPolicyObserver observer_;
323  MockDeviceManagementService device_management_service_;
324  MockCloudPolicyStore* store_;  // Not owned.
325  MockCloudExternalDataManager* external_data_manager_;  // Not owned.
326  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
327  SchemaRegistry schema_registry_;
328  scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
329  scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
330
331  // Required by ProfileHelper to get the signin Profile context.
332  scoped_ptr<TestingProfileManager> profile_manager_;
333  TestingProfile* profile_;
334  TestingProfile* signin_profile_;
335
336  static const char kSigninProfile[];
337
338 private:
339  DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
340};
341
342const char UserCloudPolicyManagerChromeOSTest::kSigninProfile[] =
343    "signin_profile";
344
345TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
346  // Tests the initialization of a manager whose Profile is waiting for the
347  // initial fetch, when the policy cache is empty.
348  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
349
350  // Initialize the CloudPolicyService without any stored data.
351  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
352  store_->NotifyStoreLoaded();
353  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
354  EXPECT_FALSE(manager_->core()->client()->is_registered());
355
356  // This starts the OAuth2 policy token fetcher using the signin Profile.
357  // The manager will then issue the registration request.
358  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
359  ASSERT_TRUE(register_request);
360
361  // Reply with a valid registration response. This triggers the initial policy
362  // fetch.
363  FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
364                         base::Unretained(register_request),
365                         DM_STATUS_SUCCESS, register_blob_));
366}
367
368TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
369  // Tests the initialization of a manager whose Profile is waiting for the
370  // initial fetch, when a previously cached policy and DMToken already exist.
371  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
372
373  // Set the initially cached data and initialize the CloudPolicyService.
374  // The initial policy fetch is issued using the cached DMToken.
375  store_->policy_.reset(new em::PolicyData(policy_data_));
376  FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
377                         base::Unretained(store_)));
378}
379
380TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
381  // Tests the initialization of a manager whose Profile is waiting for the
382  // initial fetch, when the initial store load fails.
383  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
384
385  // Initialize the CloudPolicyService without any stored data.
386  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
387  store_->NotifyStoreError();
388  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
389  EXPECT_FALSE(manager_->core()->client()->is_registered());
390
391  // This starts the OAuth2 policy token fetcher using the signin Profile.
392  // The manager will then issue the registration request.
393  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
394  ASSERT_TRUE(register_request);
395
396  // Reply with a valid registration response. This triggers the initial policy
397  // fetch.
398  FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
399                         base::Unretained(register_request),
400                         DM_STATUS_SUCCESS, register_blob_));
401}
402
403TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
404  // Tests the initialization of a manager whose Profile is waiting for the
405  // initial fetch, when the OAuth2 token fetch fails.
406  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
407
408  // Initialize the CloudPolicyService without any stored data.
409  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
410  store_->NotifyStoreLoaded();
411  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
412  EXPECT_FALSE(manager_->core()->client()->is_registered());
413
414  // This starts the OAuth2 policy token fetcher using the signin Profile.
415  // The manager will initialize with no policy after the token fetcher fails.
416  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
417
418  // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
419  // data will make it fail immediately.
420  net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
421      GaiaUrls::GetInstance()->client_login_to_oauth2_url());
422  ASSERT_TRUE(fetcher);
423  fetcher->set_response_code(400);
424  fetcher->SetResponseString("Error=BadAuthentication");
425  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
426  fetcher->delegate()->OnURLFetchComplete(fetcher);
427  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
428  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
429  Mock::VerifyAndClearExpectations(&observer_);
430}
431
432TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
433  // Tests the initialization of a manager whose Profile is waiting for the
434  // initial fetch, when the device management registration fails.
435  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
436
437  // Initialize the CloudPolicyService without any stored data.
438  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
439  store_->NotifyStoreError();
440  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
441  EXPECT_FALSE(manager_->core()->client()->is_registered());
442
443  // This starts the OAuth2 policy token fetcher using the signin Profile.
444  // The manager will then issue the registration request.
445  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
446  ASSERT_TRUE(register_request);
447
448  // Now make it fail.
449  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
450  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
451  register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
452                                 em::DeviceManagementResponse());
453  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
454  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
455  Mock::VerifyAndClearExpectations(&observer_);
456}
457
458TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
459  // Tests the initialization of a manager whose Profile is waiting for the
460  // initial fetch, when the policy fetch request fails.
461  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
462
463  // Initialize the CloudPolicyService without any stored data.
464  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
465  store_->NotifyStoreLoaded();
466  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
467  EXPECT_FALSE(manager_->core()->client()->is_registered());
468
469  // This starts the OAuth2 policy token fetcher using the signin Profile.
470  // The manager will then issue the registration request.
471  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
472  ASSERT_TRUE(register_request);
473
474  // Reply with a valid registration response. This triggers the initial policy
475  // fetch.
476  MockDeviceManagementJob* policy_request = NULL;
477  EXPECT_CALL(device_management_service_,
478              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
479      .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
480  register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
481  Mock::VerifyAndClearExpectations(&device_management_service_);
482  ASSERT_TRUE(policy_request);
483  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
484  EXPECT_TRUE(manager_->core()->client()->is_registered());
485
486  // Make the policy fetch fail. The observer gets 2 notifications: one from the
487  // RefreshPolicies callback, and another from the OnClientError callback.
488  // A single notification suffices for this edge case, but this behavior is
489  // also correct and makes the implementation simpler.
490  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
491  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
492  policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
493                               em::DeviceManagementResponse());
494  Mock::VerifyAndClearExpectations(&observer_);
495  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
496  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
497}
498
499TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) {
500  // The blocking fetch should be abandoned after the timeout.
501  ASSERT_NO_FATAL_FAILURE(CreateManager(true, 0));
502
503  // Initialize the CloudPolicyService without any stored data.
504  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
505  store_->NotifyStoreLoaded();
506  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
507  EXPECT_FALSE(manager_->core()->client()->is_registered());
508
509  // Running the message loop should trigger the timeout.
510  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
511  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
512  base::RunLoop().RunUntilIdle();
513  Mock::VerifyAndClearExpectations(&observer_);
514  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
515  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
516}
517
518
519TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
520  // Tests the first policy fetch request by a Profile that isn't managed.
521  ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
522
523  // Initialize the CloudPolicyService without any stored data. Since the
524  // manager is not waiting for the initial fetch, it will become initialized
525  // once the store is ready.
526  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
527  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
528  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
529  store_->NotifyStoreLoaded();
530  Mock::VerifyAndClearExpectations(&observer_);
531  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
532  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
533  EXPECT_FALSE(manager_->core()->client()->is_registered());
534
535  // The manager is waiting for the refresh token, and hasn't started any
536  // fetchers.
537  EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
538
539  // Set a fake refresh token at the OAuth2TokenService.
540  FakeProfileOAuth2TokenService* token_service =
541    static_cast<FakeProfileOAuth2TokenService*>(
542        ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
543  ASSERT_TRUE(token_service);
544  SigninManagerBase* signin_manager =
545      SigninManagerFactory::GetForProfile(profile_);
546  ASSERT_TRUE(signin_manager);
547  const std::string& account_id = signin_manager->GetAuthenticatedAccountId();
548  EXPECT_FALSE(token_service->RefreshTokenIsAvailable(account_id));
549  token_service->UpdateCredentials(account_id, "refresh_token");
550  EXPECT_TRUE(token_service->RefreshTokenIsAvailable(account_id));
551
552  // That should have notified the manager, which now issues the request for the
553  // policy oauth token.
554  MockDeviceManagementJob* register_request = IssueOAuthToken(true);
555  ASSERT_TRUE(register_request);
556  register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
557
558  // The refresh scheduler takes care of the initial fetch for unmanaged users.
559  // Running the task runner issues the initial fetch.
560  FetchPolicy(
561      base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
562}
563
564TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
565  // Tests a non-blocking initial policy fetch for a Profile that already has
566  // a cached DMToken.
567  ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
568
569  // Set the initially cached data and initialize the CloudPolicyService.
570  // The initial policy fetch is issued using the cached DMToken.
571  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
572  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
573  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
574  store_->policy_.reset(new em::PolicyData(policy_data_));
575  store_->NotifyStoreLoaded();
576  Mock::VerifyAndClearExpectations(&observer_);
577  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
578  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
579  EXPECT_TRUE(manager_->core()->client()->is_registered());
580
581  // The refresh scheduler takes care of the initial fetch for unmanaged users.
582  // Running the task runner issues the initial fetch.
583  FetchPolicy(
584      base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
585}
586
587}  // namespace policy
588