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