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