Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / policy / device_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/device_cloud_policy_manager_chromeos.h"
6
7 #include <algorithm>
8
9 #include "base/basictypes.h"
10 #include "base/compiler_specific.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/prefs/pref_registry_simple.h"
14 #include "base/prefs/testing_pref_service.h"
15 #include "base/run_loop.h"
16 #include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h"
17 #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h"
18 #include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
19 #include "chrome/browser/chromeos/settings/cros_settings.h"
20 #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h"
21 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
22 #include "chrome/browser/chromeos/settings/device_settings_service.h"
23 #include "chrome/browser/chromeos/settings/device_settings_test_helper.h"
24 #include "chrome/browser/prefs/browser_prefs.h"
25 #include "chrome/test/base/testing_browser_process.h"
26 #include "chromeos/cryptohome/system_salt_getter.h"
27 #include "chromeos/dbus/dbus_client_implementation_type.h"
28 #include "chromeos/dbus/dbus_thread_manager.h"
29 #include "chromeos/dbus/fake_cryptohome_client.h"
30 #include "chromeos/dbus/fake_dbus_thread_manager.h"
31 #include "chromeos/system/mock_statistics_provider.h"
32 #include "chromeos/system/statistics_provider.h"
33 #include "components/policy/core/common/cloud/cloud_policy_client.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/schema_registry.h"
37 #include "google_apis/gaia/gaia_oauth_client.h"
38 #include "net/url_request/test_url_fetcher_factory.h"
39 #include "net/url_request/url_request_test_util.h"
40 #include "policy/policy_constants.h"
41 #include "policy/proto/device_management_backend.pb.h"
42 #include "testing/gmock/include/gmock/gmock.h"
43 #include "testing/gtest/include/gtest/gtest.h"
44
45 using testing::AnyNumber;
46 using testing::AtMost;
47 using testing::DoAll;
48 using testing::Mock;
49 using testing::Return;
50 using testing::SaveArg;
51 using testing::SetArgumentPointee;
52 using testing::_;
53
54 namespace em = enterprise_management;
55
56 namespace policy {
57 namespace {
58
59 void CopyLockResult(base::RunLoop* loop,
60                     EnterpriseInstallAttributes::LockResult* out,
61                     EnterpriseInstallAttributes::LockResult result) {
62   *out = result;
63   loop->Quit();
64 }
65
66 class DeviceCloudPolicyManagerChromeOSTest
67     : public chromeos::DeviceSettingsTestBase {
68  protected:
69   DeviceCloudPolicyManagerChromeOSTest() : store_(NULL) {
70     EXPECT_CALL(mock_statistics_provider_,
71                 GetMachineStatistic(_, _))
72         .WillRepeatedly(Return(false));
73     EXPECT_CALL(mock_statistics_provider_,
74                 GetMachineStatistic("serial_number", _))
75         .WillRepeatedly(DoAll(SetArgumentPointee<1>(std::string("test_sn")),
76                               Return(true)));
77     chromeos::system::StatisticsProvider::SetTestProvider(
78         &mock_statistics_provider_);
79   }
80
81   virtual ~DeviceCloudPolicyManagerChromeOSTest() {
82     chromeos::system::StatisticsProvider::SetTestProvider(NULL);
83   }
84
85   virtual void SetUp() OVERRIDE {
86     DeviceSettingsTestBase::SetUp();
87
88     // DBusThreadManager is set up in DeviceSettingsTestBase::SetUp().
89     install_attributes_.reset(new EnterpriseInstallAttributes(
90         chromeos::DBusThreadManager::Get()->GetCryptohomeClient()));
91     store_ = new DeviceCloudPolicyStoreChromeOS(&device_settings_service_,
92                                                 install_attributes_.get(),
93                                                 loop_.message_loop_proxy());
94     manager_.reset(new DeviceCloudPolicyManagerChromeOS(
95         make_scoped_ptr(store_),
96         loop_.message_loop_proxy(),
97         loop_.message_loop_proxy(),
98         install_attributes_.get()));
99
100     chrome::RegisterLocalState(local_state_.registry());
101     manager_->Init(&schema_registry_);
102
103     // DeviceOAuth2TokenService uses the system request context to fetch
104     // OAuth tokens, then writes the token to local state, encrypting it
105     // first with methods in CryptohomeTokenEncryptor.
106     request_context_getter_ = new net::TestURLRequestContextGetter(
107         loop_.message_loop_proxy());
108     TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
109         request_context_getter_.get());
110     TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_);
111     // SystemSaltGetter is used in DeviceOAuth2TokenService.
112     chromeos::SystemSaltGetter::Initialize();
113     chromeos::DeviceOAuth2TokenServiceFactory::Initialize();
114     url_fetcher_response_code_ = 200;
115     url_fetcher_response_string_ = "{\"access_token\":\"accessToken4Test\","
116                                    "\"expires_in\":1234,"
117                                    "\"refresh_token\":\"refreshToken4Test\"}";
118   }
119
120   virtual void TearDown() OVERRIDE {
121     manager_->Shutdown();
122     DeviceSettingsTestBase::TearDown();
123
124     chromeos::DeviceOAuth2TokenServiceFactory::Shutdown();
125     chromeos::SystemSaltGetter::Shutdown();
126     TestingBrowserProcess::GetGlobal()->SetLocalState(NULL);
127   }
128
129   void LockDevice() {
130     base::RunLoop loop;
131     EnterpriseInstallAttributes::LockResult result;
132     install_attributes_->LockDevice(
133         PolicyBuilder::kFakeUsername,
134         DEVICE_MODE_ENTERPRISE,
135         PolicyBuilder::kFakeDeviceId,
136         base::Bind(&CopyLockResult, &loop, &result));
137     loop.Run();
138     ASSERT_EQ(EnterpriseInstallAttributes::LOCK_SUCCESS, result);
139   }
140
141   void VerifyPolicyPopulated() {
142     PolicyBundle bundle;
143     bundle.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
144         .Set(key::kDeviceMetricsReportingEnabled,
145              POLICY_LEVEL_MANDATORY,
146              POLICY_SCOPE_MACHINE,
147              new base::FundamentalValue(false),
148              NULL);
149     EXPECT_TRUE(manager_->policies().Equals(bundle));
150   }
151
152   scoped_ptr<EnterpriseInstallAttributes> install_attributes_;
153
154   scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
155   net::TestURLFetcherFactory url_fetcher_factory_;
156   int url_fetcher_response_code_;
157   string url_fetcher_response_string_;
158   TestingPrefServiceSimple local_state_;
159   MockDeviceManagementService device_management_service_;
160   chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
161   chromeos::ScopedTestCrosSettings test_cros_settings_;
162   chromeos::system::MockStatisticsProvider mock_statistics_provider_;
163
164   DeviceCloudPolicyStoreChromeOS* store_;
165   SchemaRegistry schema_registry_;
166   scoped_ptr<DeviceCloudPolicyManagerChromeOS> manager_;
167
168  private:
169   DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSTest);
170 };
171
172 TEST_F(DeviceCloudPolicyManagerChromeOSTest, FreshDevice) {
173   owner_key_util_->Clear();
174   FlushDeviceSettings();
175   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
176
177   manager_->Connect(&local_state_,
178                     &device_management_service_,
179                     scoped_ptr<CloudPolicyClient::StatusProvider>());
180
181   PolicyBundle bundle;
182   EXPECT_TRUE(manager_->policies().Equals(bundle));
183 }
184
185 TEST_F(DeviceCloudPolicyManagerChromeOSTest, EnrolledDevice) {
186   LockDevice();
187   FlushDeviceSettings();
188   EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
189   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
190   VerifyPolicyPopulated();
191
192   manager_->Connect(&local_state_,
193                     &device_management_service_,
194                     scoped_ptr<CloudPolicyClient::StatusProvider>());
195   VerifyPolicyPopulated();
196
197   manager_->Shutdown();
198   VerifyPolicyPopulated();
199
200   EXPECT_EQ(store_->policy()->service_account_identity(),
201             PolicyBuilder::kFakeServiceAccountIdentity);
202 }
203
204 TEST_F(DeviceCloudPolicyManagerChromeOSTest, UnmanagedDevice) {
205   device_policy_.policy_data().set_state(em::PolicyData::UNMANAGED);
206   device_policy_.Build();
207   device_settings_test_helper_.set_policy_blob(device_policy_.GetBlob());
208
209   LockDevice();
210   FlushDeviceSettings();
211   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
212   EXPECT_FALSE(store_->is_managed());
213
214   // Policy settings should be ignored for UNMANAGED devices.
215   PolicyBundle bundle;
216   EXPECT_TRUE(manager_->policies().Equals(bundle));
217
218   manager_->Connect(&local_state_,
219                     &device_management_service_,
220                     scoped_ptr<CloudPolicyClient::StatusProvider>());
221
222   // Trigger a policy refresh.
223   MockDeviceManagementJob* policy_fetch_job = NULL;
224   EXPECT_CALL(device_management_service_,
225               CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
226       .Times(AtMost(1))
227       .WillOnce(device_management_service_.CreateAsyncJob(&policy_fetch_job));
228   EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
229       .Times(AtMost(1));
230   manager_->RefreshPolicies();
231   Mock::VerifyAndClearExpectations(&device_management_service_);
232   ASSERT_TRUE(policy_fetch_job);
233
234   // Switch back to ACTIVE, service the policy fetch and let it propagate.
235   device_policy_.policy_data().set_state(em::PolicyData::ACTIVE);
236   device_policy_.Build();
237   device_settings_test_helper_.set_policy_blob(device_policy_.GetBlob());
238   em::DeviceManagementResponse policy_fetch_response;
239   policy_fetch_response.mutable_policy_response()->add_response()->CopyFrom(
240       device_policy_.policy());
241   policy_fetch_job->SendResponse(DM_STATUS_SUCCESS, policy_fetch_response);
242   FlushDeviceSettings();
243
244   // Policy state should now be active and the policy map should be populated.
245   EXPECT_TRUE(store_->is_managed());
246   VerifyPolicyPopulated();
247 }
248
249 TEST_F(DeviceCloudPolicyManagerChromeOSTest, ConsumerDevice) {
250   FlushDeviceSettings();
251   EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE, store_->status());
252   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
253
254   PolicyBundle bundle;
255   EXPECT_TRUE(manager_->policies().Equals(bundle));
256
257   manager_->Connect(&local_state_,
258                     &device_management_service_,
259                     scoped_ptr<CloudPolicyClient::StatusProvider>());
260   EXPECT_TRUE(manager_->policies().Equals(bundle));
261
262   manager_->Shutdown();
263   EXPECT_TRUE(manager_->policies().Equals(bundle));
264 }
265
266 class DeviceCloudPolicyManagerChromeOSStateKeyTest : public testing::Test {
267  protected:
268   DeviceCloudPolicyManagerChromeOSStateKeyTest() {}
269
270   virtual void SetUp() OVERRIDE {
271     chromeos::system::StatisticsProvider::SetTestProvider(
272         &statistics_provider_);
273     EXPECT_CALL(statistics_provider_, GetMachineStatistic(_, _))
274         .WillRepeatedly(Invoke(this,
275                                &DeviceCloudPolicyManagerChromeOSStateKeyTest::
276                                    GetMachineStatistic));
277   }
278
279   virtual void TearDown() OVERRIDE {
280     chromeos::system::StatisticsProvider::SetTestProvider(NULL);
281   }
282
283   bool GetMachineStatistic(const std::string& name, std::string* result) {
284     *result = "fake-" + name;
285     return true;
286   }
287
288  private:
289   chromeos::system::MockStatisticsProvider statistics_provider_;
290
291   DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSStateKeyTest);
292 };
293
294 TEST_F(DeviceCloudPolicyManagerChromeOSStateKeyTest, GetDeviceStateKeys) {
295   base::Time current = base::Time::UnixEpoch() + base::TimeDelta::FromDays(100);
296
297   // The correct number of state keys gets returned.
298   std::vector<std::string> state_keys;
299   EXPECT_TRUE(DeviceCloudPolicyManagerChromeOS::GetDeviceStateKeys(
300       current, &state_keys));
301   EXPECT_EQ(DeviceCloudPolicyManagerChromeOS::kDeviceStateKeyFutureQuanta,
302             static_cast<int>(state_keys.size()));
303
304   // All state keys are different.
305   std::set<std::string> state_key_set(state_keys.begin(), state_keys.end());
306   EXPECT_EQ(DeviceCloudPolicyManagerChromeOS::kDeviceStateKeyFutureQuanta,
307             static_cast<int>(state_key_set.size()));
308
309   // Moving forward just a little yields the same keys.
310   std::vector<std::string> new_state_keys;
311   current += base::TimeDelta::FromDays(1);
312   EXPECT_TRUE(DeviceCloudPolicyManagerChromeOS::GetDeviceStateKeys(
313       current, &new_state_keys));
314   EXPECT_EQ(state_keys, new_state_keys);
315
316   // Jumping to a future quantum results in the state keys rolling forward.
317   int64 step =
318       GG_INT64_C(1)
319       << DeviceCloudPolicyManagerChromeOS::kDeviceStateKeyTimeQuantumPower;
320   current += 2 * base::TimeDelta::FromSeconds(step);
321
322   EXPECT_TRUE(DeviceCloudPolicyManagerChromeOS::GetDeviceStateKeys(
323       current, &new_state_keys));
324   ASSERT_EQ(DeviceCloudPolicyManagerChromeOS::kDeviceStateKeyFutureQuanta,
325             static_cast<int>(new_state_keys.size()));
326   EXPECT_TRUE(std::equal(state_keys.begin() + 2, state_keys.end(),
327                          new_state_keys.begin()));
328 }
329
330 class DeviceCloudPolicyManagerChromeOSEnrollmentTest
331     : public DeviceCloudPolicyManagerChromeOSTest {
332  public:
333   void Done(EnrollmentStatus status) {
334     status_ = status;
335     done_ = true;
336   }
337
338  protected:
339   DeviceCloudPolicyManagerChromeOSEnrollmentTest()
340       : is_auto_enrollment_(false),
341         register_status_(DM_STATUS_SUCCESS),
342         policy_fetch_status_(DM_STATUS_SUCCESS),
343         robot_auth_fetch_status_(DM_STATUS_SUCCESS),
344         store_result_(true),
345         status_(EnrollmentStatus::ForStatus(EnrollmentStatus::STATUS_SUCCESS)),
346         done_(false) {}
347
348   virtual void SetUp() OVERRIDE {
349     DeviceCloudPolicyManagerChromeOSTest::SetUp();
350
351     // Set up test data.
352     device_policy_.SetDefaultNewSigningKey();
353     device_policy_.policy_data().set_timestamp(
354         (base::Time::NowFromSystemTime() -
355          base::Time::UnixEpoch()).InMilliseconds());
356     device_policy_.Build();
357
358     register_response_.mutable_register_response()->set_device_management_token(
359         PolicyBuilder::kFakeToken);
360     policy_fetch_response_.mutable_policy_response()->add_response()->CopyFrom(
361         device_policy_.policy());
362     robot_auth_fetch_response_.mutable_service_api_access_response()
363         ->set_auth_code("auth_code_for_test");
364     loaded_blob_ = device_policy_.GetBlob();
365
366     // Initialize the manager.
367     FlushDeviceSettings();
368     EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE, store_->status());
369     EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
370
371     PolicyBundle bundle;
372     EXPECT_TRUE(manager_->policies().Equals(bundle));
373
374     manager_->Connect(&local_state_,
375                       &device_management_service_,
376                       scoped_ptr<CloudPolicyClient::StatusProvider>());
377   }
378
379   void ExpectFailedEnrollment(EnrollmentStatus::Status status) {
380     EXPECT_EQ(status, status_.status());
381     EXPECT_FALSE(store_->is_managed());
382     PolicyBundle empty_bundle;
383     EXPECT_TRUE(manager_->policies().Equals(empty_bundle));
384   }
385
386   void ExpectSuccessfulEnrollment() {
387     EXPECT_EQ(EnrollmentStatus::STATUS_SUCCESS, status_.status());
388     EXPECT_EQ(DEVICE_MODE_ENTERPRISE, install_attributes_->GetMode());
389     EXPECT_TRUE(store_->has_policy());
390     EXPECT_TRUE(store_->is_managed());
391     ASSERT_TRUE(manager_->core()->client());
392     EXPECT_TRUE(manager_->core()->client()->is_registered());
393
394     VerifyPolicyPopulated();
395   }
396
397   void RunTest() {
398     // Trigger enrollment.
399     MockDeviceManagementJob* register_job = NULL;
400     EXPECT_CALL(device_management_service_,
401                 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
402         .Times(AtMost(1))
403         .WillOnce(device_management_service_.CreateAsyncJob(&register_job));
404     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
405         .Times(AtMost(1))
406         .WillOnce(DoAll(SaveArg<5>(&client_id_),
407                         SaveArg<6>(&register_request_)));
408     DeviceCloudPolicyManagerChromeOS::AllowedDeviceModes modes;
409     modes[DEVICE_MODE_ENTERPRISE] = true;
410     manager_->StartEnrollment(
411         "auth token", is_auto_enrollment_, modes,
412         base::Bind(&DeviceCloudPolicyManagerChromeOSEnrollmentTest::Done,
413                    base::Unretained(this)));
414     Mock::VerifyAndClearExpectations(&device_management_service_);
415
416     if (done_)
417       return;
418
419     // Process registration.
420     ASSERT_TRUE(register_job);
421     MockDeviceManagementJob* policy_fetch_job = NULL;
422     EXPECT_CALL(device_management_service_,
423                 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
424         .Times(AtMost(1))
425         .WillOnce(device_management_service_.CreateAsyncJob(&policy_fetch_job));
426     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
427         .Times(AtMost(1));
428     register_job->SendResponse(register_status_, register_response_);
429     Mock::VerifyAndClearExpectations(&device_management_service_);
430
431     if (done_)
432       return;
433
434     // Process policy fetch.
435     ASSERT_TRUE(policy_fetch_job);
436     policy_fetch_job->SendResponse(policy_fetch_status_,
437                                    policy_fetch_response_);
438
439     if (done_)
440       return;
441
442     // Process verification.
443     MockDeviceManagementJob* robot_auth_fetch_job = NULL;
444     EXPECT_CALL(device_management_service_, CreateJob(
445         DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH, _))
446         .Times(AtMost(1))
447         .WillOnce(device_management_service_.CreateAsyncJob(
448             &robot_auth_fetch_job));
449     EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
450         .Times(AtMost(1));
451     base::RunLoop().RunUntilIdle();
452     Mock::VerifyAndClearExpectations(&device_management_service_);
453
454     if (done_)
455       return;
456
457     // Process robot auth token fetch.
458     ASSERT_TRUE(robot_auth_fetch_job);
459     robot_auth_fetch_job->SendResponse(robot_auth_fetch_status_,
460                                        robot_auth_fetch_response_);
461     Mock::VerifyAndClearExpectations(&device_management_service_);
462
463     if (done_)
464       return;
465
466     // Process robot refresh token fetch if the auth code fetch succeeded.
467     // DeviceCloudPolicyManagerChromeOS holds an EnrollmentHandlerChromeOS which
468     // holds a GaiaOAuthClient that fetches the refresh token during enrollment.
469     // We return a successful OAuth response via a TestURLFetcher to trigger the
470     // happy path for these classes so that enrollment can continue.
471     if (robot_auth_fetch_status_ == DM_STATUS_SUCCESS) {
472       net::TestURLFetcher* url_fetcher = url_fetcher_factory_.GetFetcherByID(
473           gaia::GaiaOAuthClient::kUrlFetcherId);
474       ASSERT_TRUE(url_fetcher);
475       url_fetcher->SetMaxRetriesOn5xx(0);
476       url_fetcher->set_status(net::URLRequestStatus());
477       url_fetcher->set_response_code(url_fetcher_response_code_);
478       url_fetcher->SetResponseString(url_fetcher_response_string_);
479       url_fetcher->delegate()->OnURLFetchComplete(url_fetcher);
480     }
481     base::RunLoop().RunUntilIdle();
482
483     if (done_)
484       return;
485
486     // Process robot refresh token store.
487     chromeos::DeviceOAuth2TokenService* token_service =
488         chromeos::DeviceOAuth2TokenServiceFactory::Get();
489     EXPECT_TRUE(token_service->RefreshTokenIsAvailable(
490         token_service->GetRobotAccountId()));
491
492     // Process policy store.
493     device_settings_test_helper_.set_store_result(store_result_);
494     device_settings_test_helper_.FlushStore();
495     EXPECT_EQ(device_policy_.GetBlob(),
496               device_settings_test_helper_.policy_blob());
497
498     if (done_)
499       return;
500
501     // Key installation and policy load.
502     device_settings_test_helper_.set_policy_blob(loaded_blob_);
503     owner_key_util_->SetPublicKeyFromPrivateKey(
504         *device_policy_.GetNewSigningKey());
505     ReloadDeviceSettings();
506   }
507
508   bool is_auto_enrollment_;
509
510   DeviceManagementStatus register_status_;
511   em::DeviceManagementResponse register_response_;
512
513   DeviceManagementStatus policy_fetch_status_;
514   em::DeviceManagementResponse policy_fetch_response_;
515
516   DeviceManagementStatus robot_auth_fetch_status_;
517   em::DeviceManagementResponse robot_auth_fetch_response_;
518
519   bool store_result_;
520   std::string loaded_blob_;
521
522   em::DeviceManagementRequest register_request_;
523   std::string client_id_;
524   EnrollmentStatus status_;
525
526   bool done_;
527
528  private:
529   DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSEnrollmentTest);
530 };
531
532 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, Success) {
533   RunTest();
534   ExpectSuccessfulEnrollment();
535 }
536
537 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, AutoEnrollment) {
538   is_auto_enrollment_ = true;
539   RunTest();
540   ExpectSuccessfulEnrollment();
541   EXPECT_TRUE(register_request_.register_request().auto_enrolled());
542 }
543
544 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, Reenrollment) {
545   LockDevice();
546
547   RunTest();
548   ExpectSuccessfulEnrollment();
549   EXPECT_TRUE(register_request_.register_request().reregister());
550   EXPECT_EQ(PolicyBuilder::kFakeDeviceId, client_id_);
551 }
552
553 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, RegistrationFailed) {
554   register_status_ = DM_STATUS_REQUEST_FAILED;
555   RunTest();
556   ExpectFailedEnrollment(EnrollmentStatus::STATUS_REGISTRATION_FAILED);
557   EXPECT_EQ(DM_STATUS_REQUEST_FAILED, status_.client_status());
558 }
559
560 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
561        RobotAuthCodeFetchFailed) {
562   robot_auth_fetch_status_ = DM_STATUS_REQUEST_FAILED;
563   RunTest();
564   ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_AUTH_FETCH_FAILED);
565 }
566
567 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
568        RobotRefreshTokenFetchResponseCodeFailed) {
569   url_fetcher_response_code_ = 400;
570   RunTest();
571   ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED);
572   EXPECT_EQ(400, status_.http_status());
573 }
574
575 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
576        RobotRefreshTokenFetchResponseStringFailed) {
577   url_fetcher_response_string_ = "invalid response json";
578   RunTest();
579   ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED);
580 }
581
582 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
583        RobotRefreshEncryptionFailed) {
584   // The encryption lib is a noop for tests, but empty results from encryption
585   // is an error, so we simulate an encryption error by returning an empty
586   // refresh token.
587   url_fetcher_response_string_ = "{\"access_token\":\"accessToken4Test\","
588                                  "\"expires_in\":1234,"
589                                  "\"refresh_token\":\"\"}";
590   RunTest();
591   ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED);
592 }
593
594 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, PolicyFetchFailed) {
595   policy_fetch_status_ = DM_STATUS_REQUEST_FAILED;
596   RunTest();
597   ExpectFailedEnrollment(EnrollmentStatus::STATUS_POLICY_FETCH_FAILED);
598   EXPECT_EQ(DM_STATUS_REQUEST_FAILED, status_.client_status());
599 }
600
601 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, ValidationFailed) {
602   device_policy_.policy().set_policy_data_signature("bad");
603   policy_fetch_response_.clear_policy_response();
604   policy_fetch_response_.mutable_policy_response()->add_response()->CopyFrom(
605       device_policy_.policy());
606   RunTest();
607   ExpectFailedEnrollment(EnrollmentStatus::STATUS_VALIDATION_FAILED);
608   EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_BAD_INITIAL_SIGNATURE,
609             status_.validation_status());
610 }
611
612 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, StoreError) {
613   store_result_ = false;
614   RunTest();
615   ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR);
616   EXPECT_EQ(CloudPolicyStore::STATUS_STORE_ERROR,
617             status_.store_status());
618 }
619
620 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, LoadError) {
621   loaded_blob_.clear();
622   RunTest();
623   ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR);
624   EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR,
625             status_.store_status());
626 }
627
628 // A subclass that runs with a blank system salt.
629 class DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest
630     : public DeviceCloudPolicyManagerChromeOSEnrollmentTest {
631  protected:
632   DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest() {
633     // Set up a FakeCryptohomeClient with a blank system salt.
634     scoped_ptr<chromeos::FakeCryptohomeClient> fake_cryptohome_client(
635         new chromeos::FakeCryptohomeClient());
636     fake_cryptohome_client->set_system_salt(std::vector<uint8>());
637     fake_dbus_thread_manager_->SetCryptohomeClient(
638         fake_cryptohome_client.PassAs<chromeos::CryptohomeClient>());
639   }
640 };
641
642 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest,
643        RobotRefreshSaveFailed) {
644   // Without the system salt, the robot token can't be stored.
645   RunTest();
646   ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED);
647 }
648
649 }  // namespace
650 }  // namespace policy