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