Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / device_cloud_policy_manager_chromeos_unittest.cc
blob4d8c5f4963dd54afb11d0eb2af4288327abd4a4b
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.
5 #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
7 #include <algorithm>
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/ownership/owner_settings_service_chromeos.h"
19 #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
20 #include "chrome/browser/chromeos/policy/device_cloud_policy_initializer.h"
21 #include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h"
22 #include "chrome/browser/chromeos/policy/enrollment_config.h"
23 #include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h"
24 #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h"
25 #include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
26 #include "chrome/browser/chromeos/settings/cros_settings.h"
27 #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h"
28 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
29 #include "chrome/browser/chromeos/settings/device_settings_service.h"
30 #include "chrome/browser/chromeos/settings/device_settings_test_helper.h"
31 #include "chrome/browser/prefs/browser_prefs.h"
32 #include "chrome/test/base/testing_browser_process.h"
33 #include "chrome/test/base/testing_profile.h"
34 #include "chromeos/cryptohome/system_salt_getter.h"
35 #include "chromeos/dbus/dbus_client_implementation_type.h"
36 #include "chromeos/dbus/dbus_thread_manager.h"
37 #include "chromeos/dbus/fake_cryptohome_client.h"
38 #include "chromeos/dbus/fake_session_manager_client.h"
39 #include "chromeos/system/fake_statistics_provider.h"
40 #include "chromeos/system/statistics_provider.h"
41 #include "components/policy/core/common/cloud/cloud_policy_client.h"
42 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
43 #include "components/policy/core/common/cloud/cloud_policy_core.h"
44 #include "components/policy/core/common/cloud/mock_device_management_service.h"
45 #include "components/policy/core/common/external_data_fetcher.h"
46 #include "components/policy/core/common/schema_registry.h"
47 #include "google_apis/gaia/gaia_oauth_client.h"
48 #include "net/url_request/test_url_fetcher_factory.h"
49 #include "net/url_request/url_request_test_util.h"
50 #include "policy/policy_constants.h"
51 #include "policy/proto/device_management_backend.pb.h"
52 #include "testing/gmock/include/gmock/gmock.h"
53 #include "testing/gtest/include/gtest/gtest.h"
55 using testing::AnyNumber;
56 using testing::AtMost;
57 using testing::DoAll;
58 using testing::Mock;
59 using testing::Return;
60 using testing::SaveArg;
61 using testing::SetArgumentPointee;
62 using testing::_;
64 namespace em = enterprise_management;
66 namespace policy {
67 namespace {
69 void CopyLockResult(base::RunLoop* loop,
70 EnterpriseInstallAttributes::LockResult* out,
71 EnterpriseInstallAttributes::LockResult result) {
72 *out = result;
73 loop->Quit();
76 class TestingDeviceCloudPolicyManagerChromeOS
77 : public DeviceCloudPolicyManagerChromeOS {
78 public:
79 TestingDeviceCloudPolicyManagerChromeOS(
80 scoped_ptr<DeviceCloudPolicyStoreChromeOS> store,
81 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
82 ServerBackedStateKeysBroker* state_keys_broker)
83 : DeviceCloudPolicyManagerChromeOS(
84 store.Pass(), task_runner, state_keys_broker) {}
85 ~TestingDeviceCloudPolicyManagerChromeOS() override {}
88 class DeviceCloudPolicyManagerChromeOSTest
89 : public chromeos::DeviceSettingsTestBase,
90 public DeviceCloudPolicyManagerChromeOS::Observer {
91 protected:
92 DeviceCloudPolicyManagerChromeOSTest()
93 : fake_cryptohome_client_(new chromeos::FakeCryptohomeClient()),
94 state_keys_broker_(&fake_session_manager_client_,
95 base::MessageLoopProxy::current()),
96 store_(NULL) {
97 fake_statistics_provider_.SetMachineStatistic("serial_numer", "test_sn");
98 std::vector<std::string> state_keys;
99 state_keys.push_back("1");
100 state_keys.push_back("2");
101 state_keys.push_back("3");
102 fake_session_manager_client_.set_server_backed_state_keys(state_keys);
105 ~DeviceCloudPolicyManagerChromeOSTest() override {
106 chromeos::system::StatisticsProvider::SetTestProvider(NULL);
109 void SetUp() override {
110 DeviceSettingsTestBase::SetUp();
112 dbus_setter_->SetCryptohomeClient(
113 scoped_ptr<chromeos::CryptohomeClient>(fake_cryptohome_client_));
115 install_attributes_.reset(
116 new EnterpriseInstallAttributes(fake_cryptohome_client_));
117 store_ =
118 new DeviceCloudPolicyStoreChromeOS(&device_settings_service_,
119 install_attributes_.get(),
120 base::MessageLoopProxy::current());
121 manager_.reset(new TestingDeviceCloudPolicyManagerChromeOS(
122 make_scoped_ptr(store_),
123 base::MessageLoopProxy::current(),
124 &state_keys_broker_));
126 chrome::RegisterLocalState(local_state_.registry());
127 manager_->Init(&schema_registry_);
129 // DeviceOAuth2TokenService uses the system request context to fetch
130 // OAuth tokens, then writes the token to local state, encrypting it
131 // first with methods in CryptohomeTokenEncryptor.
132 request_context_getter_ = new net::TestURLRequestContextGetter(
133 base::MessageLoopProxy::current());
134 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
135 request_context_getter_.get());
136 TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_);
137 // SystemSaltGetter is used in DeviceOAuth2TokenService.
138 chromeos::SystemSaltGetter::Initialize();
139 chromeos::DeviceOAuth2TokenServiceFactory::Initialize();
140 url_fetcher_response_code_ = 200;
141 url_fetcher_response_string_ = "{\"access_token\":\"accessToken4Test\","
142 "\"expires_in\":1234,"
143 "\"refresh_token\":\"refreshToken4Test\"}";
146 void TearDown() override {
147 manager_->RemoveDeviceCloudPolicyManagerObserver(this);
148 manager_->Shutdown();
149 if (initializer_)
150 initializer_->Shutdown();
151 DeviceSettingsTestBase::TearDown();
153 chromeos::DeviceOAuth2TokenServiceFactory::Shutdown();
154 chromeos::SystemSaltGetter::Shutdown();
155 TestingBrowserProcess::GetGlobal()->SetLocalState(NULL);
158 void LockDevice() {
159 base::RunLoop loop;
160 EnterpriseInstallAttributes::LockResult result;
161 install_attributes_->LockDevice(
162 PolicyBuilder::kFakeUsername,
163 DEVICE_MODE_ENTERPRISE,
164 PolicyBuilder::kFakeDeviceId,
165 base::Bind(&CopyLockResult, &loop, &result));
166 loop.Run();
167 ASSERT_EQ(EnterpriseInstallAttributes::LOCK_SUCCESS, result);
170 void ConnectManager() {
171 manager_->Initialize(&local_state_);
172 manager_->AddDeviceCloudPolicyManagerObserver(this);
173 initializer_.reset(new DeviceCloudPolicyInitializer(
174 &local_state_,
175 &device_management_service_,
176 &consumer_device_management_service_,
177 base::MessageLoopProxy::current(),
178 install_attributes_.get(),
179 &state_keys_broker_,
180 store_,
181 manager_.get()));
182 initializer_->Init();
185 void VerifyPolicyPopulated() {
186 PolicyBundle bundle;
187 bundle.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
188 .Set(key::kDeviceMetricsReportingEnabled,
189 POLICY_LEVEL_MANDATORY,
190 POLICY_SCOPE_MACHINE,
191 new base::FundamentalValue(false),
192 NULL);
193 EXPECT_TRUE(manager_->policies().Equals(bundle));
196 MOCK_METHOD0(OnDeviceCloudPolicyManagerConnected, void());
197 MOCK_METHOD0(OnDeviceCloudPolicyManagerDisconnected, void());
199 scoped_ptr<EnterpriseInstallAttributes> install_attributes_;
201 scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
202 net::TestURLFetcherFactory url_fetcher_factory_;
203 int url_fetcher_response_code_;
204 std::string url_fetcher_response_string_;
205 TestingPrefServiceSimple local_state_;
206 MockDeviceManagementService device_management_service_;
207 MockDeviceManagementService consumer_device_management_service_;
208 chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
209 chromeos::ScopedTestCrosSettings test_cros_settings_;
210 chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_;
211 chromeos::FakeSessionManagerClient fake_session_manager_client_;
212 chromeos::FakeCryptohomeClient* fake_cryptohome_client_;
213 ServerBackedStateKeysBroker state_keys_broker_;
215 DeviceCloudPolicyStoreChromeOS* store_;
216 SchemaRegistry schema_registry_;
217 scoped_ptr<TestingDeviceCloudPolicyManagerChromeOS> manager_;
218 scoped_ptr<DeviceCloudPolicyInitializer> initializer_;
220 private:
221 DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSTest);
224 TEST_F(DeviceCloudPolicyManagerChromeOSTest, FreshDevice) {
225 owner_key_util_->Clear();
226 FlushDeviceSettings();
227 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
229 manager_->Initialize(&local_state_);
231 PolicyBundle bundle;
232 EXPECT_TRUE(manager_->policies().Equals(bundle));
235 TEST_F(DeviceCloudPolicyManagerChromeOSTest, EnrolledDevice) {
236 LockDevice();
237 FlushDeviceSettings();
238 EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
239 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
240 VerifyPolicyPopulated();
242 // Trigger a policy refresh - this triggers a policy update.
243 MockDeviceManagementJob* policy_fetch_job = NULL;
244 EXPECT_CALL(device_management_service_,
245 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
246 .Times(AtMost(1))
247 .WillOnce(device_management_service_.CreateAsyncJob(&policy_fetch_job));
248 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
249 .Times(AtMost(1));
250 ConnectManager();
251 base::RunLoop().RunUntilIdle();
252 Mock::VerifyAndClearExpectations(&device_management_service_);
253 ASSERT_TRUE(policy_fetch_job);
254 // Should create a status uploader for reporting on enrolled devices.
255 EXPECT_TRUE(manager_->HasStatusUploaderForTest());
256 VerifyPolicyPopulated();
258 manager_->Shutdown();
259 VerifyPolicyPopulated();
261 EXPECT_EQ(store_->policy()->service_account_identity(),
262 PolicyBuilder::kFakeServiceAccountIdentity);
265 TEST_F(DeviceCloudPolicyManagerChromeOSTest, UnmanagedDevice) {
266 device_policy_.policy_data().set_state(em::PolicyData::UNMANAGED);
267 device_policy_.Build();
268 device_settings_test_helper_.set_policy_blob(device_policy_.GetBlob());
270 LockDevice();
271 FlushDeviceSettings();
272 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
273 EXPECT_FALSE(store_->is_managed());
275 // Policy settings should be ignored for UNMANAGED devices.
276 PolicyBundle bundle;
277 EXPECT_TRUE(manager_->policies().Equals(bundle));
279 // Trigger a policy refresh.
280 MockDeviceManagementJob* policy_fetch_job = NULL;
281 EXPECT_CALL(device_management_service_,
282 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
283 .Times(AtMost(1))
284 .WillOnce(device_management_service_.CreateAsyncJob(&policy_fetch_job));
285 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
286 .Times(AtMost(1));
287 ConnectManager();
288 base::RunLoop().RunUntilIdle();
289 Mock::VerifyAndClearExpectations(&device_management_service_);
290 ASSERT_TRUE(policy_fetch_job);
291 // Should create a status provider for reporting on enrolled devices, even
292 // those that aren't managed.
293 EXPECT_TRUE(manager_->HasStatusUploaderForTest());
295 // Switch back to ACTIVE, service the policy fetch and let it propagate.
296 device_policy_.policy_data().set_state(em::PolicyData::ACTIVE);
297 device_policy_.Build();
298 device_settings_test_helper_.set_policy_blob(device_policy_.GetBlob());
299 em::DeviceManagementResponse policy_fetch_response;
300 policy_fetch_response.mutable_policy_response()->add_response()->CopyFrom(
301 device_policy_.policy());
302 policy_fetch_job->SendResponse(DM_STATUS_SUCCESS, policy_fetch_response);
303 FlushDeviceSettings();
305 // Policy state should now be active and the policy map should be populated.
306 EXPECT_TRUE(store_->is_managed());
307 VerifyPolicyPopulated();
310 TEST_F(DeviceCloudPolicyManagerChromeOSTest, ConsumerDevice) {
311 FlushDeviceSettings();
312 EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE, store_->status());
313 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
315 PolicyBundle bundle;
316 EXPECT_TRUE(manager_->policies().Equals(bundle));
318 ConnectManager();
319 EXPECT_TRUE(manager_->policies().Equals(bundle));
320 // Should not create a status provider for reporting on consumer devices.
321 EXPECT_FALSE(manager_->HasStatusUploaderForTest());
323 manager_->Shutdown();
324 EXPECT_TRUE(manager_->policies().Equals(bundle));
327 TEST_F(DeviceCloudPolicyManagerChromeOSTest, ConnectAndDisconnect) {
328 LockDevice();
329 FlushDeviceSettings();
330 EXPECT_FALSE(manager_->core()->service()); // Not connected.
332 // Connect the manager.
333 MockDeviceManagementJob* policy_fetch_job = nullptr;
334 EXPECT_CALL(device_management_service_,
335 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
336 .WillOnce(device_management_service_.CreateAsyncJob(&policy_fetch_job));
337 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _));
338 EXPECT_CALL(*this, OnDeviceCloudPolicyManagerConnected());
339 ConnectManager();
340 base::RunLoop().RunUntilIdle();
341 Mock::VerifyAndClearExpectations(&device_management_service_);
342 Mock::VerifyAndClearExpectations(this);
343 EXPECT_TRUE(manager_->core()->service()); // Connected.
345 // Disconnect the manager.
346 EXPECT_CALL(*this, OnDeviceCloudPolicyManagerDisconnected());
347 manager_->Disconnect();
348 EXPECT_FALSE(manager_->core()->service()); // Not connnected.
351 class DeviceCloudPolicyManagerChromeOSEnrollmentTest
352 : public DeviceCloudPolicyManagerChromeOSTest {
353 public:
354 void Done(EnrollmentStatus status) {
355 status_ = status;
356 done_ = true;
359 MOCK_METHOD1(OnUnregistered, void(bool));
361 protected:
362 DeviceCloudPolicyManagerChromeOSEnrollmentTest()
363 : management_mode_(MANAGEMENT_MODE_ENTERPRISE_MANAGED),
364 register_status_(DM_STATUS_SUCCESS),
365 policy_fetch_status_(DM_STATUS_SUCCESS),
366 robot_auth_fetch_status_(DM_STATUS_SUCCESS),
367 store_result_(true),
368 status_(EnrollmentStatus::ForStatus(EnrollmentStatus::STATUS_SUCCESS)),
369 done_(false) {}
371 void SetUp() override {
372 DeviceCloudPolicyManagerChromeOSTest::SetUp();
374 // Set up test data.
375 device_policy_.SetDefaultNewSigningKey();
376 device_policy_.policy_data().set_timestamp(
377 (base::Time::NowFromSystemTime() -
378 base::Time::UnixEpoch()).InMilliseconds());
379 device_policy_.Build();
381 register_response_.mutable_register_response()->set_device_management_token(
382 PolicyBuilder::kFakeToken);
383 policy_fetch_response_.mutable_policy_response()->add_response()->CopyFrom(
384 device_policy_.policy());
385 robot_auth_fetch_response_.mutable_service_api_access_response()
386 ->set_auth_code("auth_code_for_test");
387 loaded_blob_ = device_policy_.GetBlob();
389 // Initialize the manager.
390 FlushDeviceSettings();
391 EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE, store_->status());
392 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
394 PolicyBundle bundle;
395 EXPECT_TRUE(manager_->policies().Equals(bundle));
397 ConnectManager();
400 void ExpectFailedEnrollment(EnrollmentStatus::Status status) {
401 EXPECT_EQ(status, status_.status());
402 EXPECT_FALSE(store_->is_managed());
403 PolicyBundle empty_bundle;
404 EXPECT_TRUE(manager_->policies().Equals(empty_bundle));
407 void ExpectSuccessfulEnrollment() {
408 EXPECT_EQ(EnrollmentStatus::STATUS_SUCCESS, status_.status());
409 ASSERT_TRUE(manager_->core()->client());
410 EXPECT_TRUE(manager_->core()->client()->is_registered());
412 if (management_mode_ != MANAGEMENT_MODE_CONSUMER_MANAGED) {
413 EXPECT_EQ(DEVICE_MODE_ENTERPRISE, install_attributes_->GetMode());
414 EXPECT_TRUE(store_->has_policy());
415 EXPECT_TRUE(store_->is_managed());
416 VerifyPolicyPopulated();
420 void RunTest() {
421 // Trigger enrollment.
422 MockDeviceManagementJob* register_job = NULL;
423 EXPECT_CALL(device_management_service_,
424 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
425 .Times(AtMost(1))
426 .WillOnce(device_management_service_.CreateAsyncJob(&register_job));
427 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
428 .Times(AtMost(1))
429 .WillOnce(DoAll(SaveArg<5>(&client_id_),
430 SaveArg<6>(&register_request_)));
431 DeviceCloudPolicyInitializer::AllowedDeviceModes modes;
432 modes[DEVICE_MODE_ENTERPRISE] = true;
434 chromeos::OwnerSettingsServiceChromeOS* owner_settings_service =
435 chromeos::OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(
436 profile_.get());
437 ASSERT_TRUE(owner_settings_service);
439 EnrollmentConfig enrollment_config;
440 enrollment_config.mode = EnrollmentConfig::MODE_MANUAL;
441 initializer_->StartEnrollment(
442 management_mode_, &device_management_service_, owner_settings_service,
443 enrollment_config, "auth token", modes,
444 base::Bind(&DeviceCloudPolicyManagerChromeOSEnrollmentTest::Done,
445 base::Unretained(this)));
446 base::RunLoop().RunUntilIdle();
447 Mock::VerifyAndClearExpectations(&device_management_service_);
449 if (done_)
450 return;
452 // Process registration.
453 ASSERT_TRUE(register_job);
454 MockDeviceManagementJob* policy_fetch_job = NULL;
455 EXPECT_CALL(device_management_service_,
456 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
457 .Times(AtMost(1))
458 .WillOnce(device_management_service_.CreateAsyncJob(&policy_fetch_job));
459 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
460 .Times(AtMost(1));
461 register_job->SendResponse(register_status_, register_response_);
462 Mock::VerifyAndClearExpectations(&device_management_service_);
464 if (done_)
465 return;
467 // Process policy fetch.
468 ASSERT_TRUE(policy_fetch_job);
469 policy_fetch_job->SendResponse(policy_fetch_status_,
470 policy_fetch_response_);
472 if (done_)
473 return;
475 // Process verification.
476 MockDeviceManagementJob* robot_auth_fetch_job = NULL;
477 EXPECT_CALL(device_management_service_, CreateJob(
478 DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH, _))
479 .Times(AtMost(1))
480 .WillOnce(device_management_service_.CreateAsyncJob(
481 &robot_auth_fetch_job));
482 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
483 .Times(AtMost(1));
484 base::RunLoop().RunUntilIdle();
485 Mock::VerifyAndClearExpectations(&device_management_service_);
487 if (done_)
488 return;
490 // Process robot auth token fetch.
491 ASSERT_TRUE(robot_auth_fetch_job);
492 robot_auth_fetch_job->SendResponse(robot_auth_fetch_status_,
493 robot_auth_fetch_response_);
494 Mock::VerifyAndClearExpectations(&device_management_service_);
496 if (done_)
497 return;
499 // Process robot refresh token fetch if the auth code fetch succeeded.
500 // DeviceCloudPolicyInitializer holds an EnrollmentHandlerChromeOS which
501 // holds a GaiaOAuthClient that fetches the refresh token during enrollment.
502 // We return a successful OAuth response via a TestURLFetcher to trigger the
503 // happy path for these classes so that enrollment can continue.
504 if (robot_auth_fetch_status_ == DM_STATUS_SUCCESS) {
505 net::TestURLFetcher* url_fetcher = url_fetcher_factory_.GetFetcherByID(
506 gaia::GaiaOAuthClient::kUrlFetcherId);
507 ASSERT_TRUE(url_fetcher);
508 url_fetcher->SetMaxRetriesOn5xx(0);
509 url_fetcher->set_status(net::URLRequestStatus());
510 url_fetcher->set_response_code(url_fetcher_response_code_);
511 url_fetcher->SetResponseString(url_fetcher_response_string_);
512 url_fetcher->delegate()->OnURLFetchComplete(url_fetcher);
515 if (management_mode_ == MANAGEMENT_MODE_CONSUMER_MANAGED)
516 FlushDeviceSettings();
517 else
518 base::RunLoop().RunUntilIdle();
520 if (done_)
521 return;
523 // Process robot refresh token store.
524 chromeos::DeviceOAuth2TokenService* token_service =
525 chromeos::DeviceOAuth2TokenServiceFactory::Get();
526 EXPECT_TRUE(token_service->RefreshTokenIsAvailable(
527 token_service->GetRobotAccountId()));
529 // Process policy store.
530 device_settings_test_helper_.set_store_result(store_result_);
531 device_settings_test_helper_.FlushStore();
532 EXPECT_EQ(device_policy_.GetBlob(),
533 device_settings_test_helper_.policy_blob());
535 if (done_)
536 return;
538 // Key installation and policy load.
539 device_settings_test_helper_.set_policy_blob(loaded_blob_);
540 owner_key_util_->SetPublicKeyFromPrivateKey(
541 *device_policy_.GetNewSigningKey());
542 ReloadDeviceSettings();
545 ManagementMode management_mode_;
547 DeviceManagementStatus register_status_;
548 em::DeviceManagementResponse register_response_;
550 DeviceManagementStatus policy_fetch_status_;
551 em::DeviceManagementResponse policy_fetch_response_;
553 DeviceManagementStatus robot_auth_fetch_status_;
554 em::DeviceManagementResponse robot_auth_fetch_response_;
556 bool store_result_;
557 std::string loaded_blob_;
559 em::DeviceManagementRequest register_request_;
560 std::string client_id_;
561 EnrollmentStatus status_;
563 bool done_;
565 private:
566 DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSEnrollmentTest);
569 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, Success) {
570 RunTest();
571 ExpectSuccessfulEnrollment();
574 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, Reenrollment) {
575 LockDevice();
577 RunTest();
578 ExpectSuccessfulEnrollment();
579 EXPECT_TRUE(register_request_.register_request().reregister());
580 EXPECT_EQ(PolicyBuilder::kFakeDeviceId, client_id_);
583 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, RegistrationFailed) {
584 register_status_ = DM_STATUS_REQUEST_FAILED;
585 RunTest();
586 ExpectFailedEnrollment(EnrollmentStatus::STATUS_REGISTRATION_FAILED);
587 EXPECT_EQ(DM_STATUS_REQUEST_FAILED, status_.client_status());
590 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
591 RobotAuthCodeFetchFailed) {
592 robot_auth_fetch_status_ = DM_STATUS_REQUEST_FAILED;
593 RunTest();
594 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_AUTH_FETCH_FAILED);
597 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
598 RobotRefreshTokenFetchResponseCodeFailed) {
599 url_fetcher_response_code_ = 400;
600 RunTest();
601 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED);
602 EXPECT_EQ(400, status_.http_status());
605 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
606 RobotRefreshTokenFetchResponseStringFailed) {
607 url_fetcher_response_string_ = "invalid response json";
608 RunTest();
609 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED);
612 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
613 RobotRefreshEncryptionFailed) {
614 // The encryption lib is a noop for tests, but empty results from encryption
615 // is an error, so we simulate an encryption error by returning an empty
616 // refresh token.
617 url_fetcher_response_string_ = "{\"access_token\":\"accessToken4Test\","
618 "\"expires_in\":1234,"
619 "\"refresh_token\":\"\"}";
620 RunTest();
621 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED);
624 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, PolicyFetchFailed) {
625 policy_fetch_status_ = DM_STATUS_REQUEST_FAILED;
626 RunTest();
627 ExpectFailedEnrollment(EnrollmentStatus::STATUS_POLICY_FETCH_FAILED);
628 EXPECT_EQ(DM_STATUS_REQUEST_FAILED, status_.client_status());
631 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, ValidationFailed) {
632 device_policy_.policy().set_policy_data_signature("bad");
633 policy_fetch_response_.clear_policy_response();
634 policy_fetch_response_.mutable_policy_response()->add_response()->CopyFrom(
635 device_policy_.policy());
636 RunTest();
637 ExpectFailedEnrollment(EnrollmentStatus::STATUS_VALIDATION_FAILED);
638 EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_BAD_INITIAL_SIGNATURE,
639 status_.validation_status());
642 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, StoreError) {
643 store_result_ = false;
644 RunTest();
645 ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR);
646 EXPECT_EQ(CloudPolicyStore::STATUS_STORE_ERROR,
647 status_.store_status());
650 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, LoadError) {
651 loaded_blob_.clear();
652 RunTest();
653 ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR);
654 EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR,
655 status_.store_status());
658 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest,
659 SuccessfulConsumerManagementEnrollment) {
660 management_mode_ = MANAGEMENT_MODE_CONSUMER_MANAGED;
661 owner_key_util_->SetPrivateKey(device_policy_.GetNewSigningKey());
662 InitOwner(device_policy_.policy_data().username(), true);
663 FlushDeviceSettings();
665 device_policy_.policy_data().set_management_mode(em::PolicyData::LOCAL_OWNER);
666 device_policy_.Build();
667 device_settings_test_helper_.set_policy_blob(device_policy_.GetBlob());
668 ReloadDeviceSettings();
670 RunTest();
671 ExpectSuccessfulEnrollment();
674 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, UnregisterSucceeds) {
675 // Enroll first.
676 RunTest();
677 ExpectSuccessfulEnrollment();
679 // Set up mock objects for the upcoming unregistration job.
680 em::DeviceManagementResponse response;
681 response.mutable_unregister_response();
682 EXPECT_CALL(device_management_service_,
683 CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, _))
684 .WillOnce(device_management_service_.SucceedJob(response));
685 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _));
686 EXPECT_CALL(*this, OnUnregistered(true));
688 // Start unregistering.
689 manager_->Unregister(base::Bind(
690 &DeviceCloudPolicyManagerChromeOSEnrollmentTest::OnUnregistered,
691 base::Unretained(this)));
694 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest, UnregisterFails) {
695 // Enroll first.
696 RunTest();
697 ExpectSuccessfulEnrollment();
699 // Set up mock objects for the upcoming unregistration job.
700 EXPECT_CALL(device_management_service_,
701 CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, _))
702 .WillOnce(device_management_service_.FailJob(DM_STATUS_REQUEST_FAILED));
703 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _));
704 EXPECT_CALL(*this, OnUnregistered(false));
706 // Start unregistering.
707 manager_->Unregister(base::Bind(
708 &DeviceCloudPolicyManagerChromeOSEnrollmentTest::OnUnregistered,
709 base::Unretained(this)));
712 // A subclass that runs with a blank system salt.
713 class DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest
714 : public DeviceCloudPolicyManagerChromeOSEnrollmentTest {
715 protected:
716 DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest() {
717 // Set up a FakeCryptohomeClient with a blank system salt.
718 fake_cryptohome_client_->set_system_salt(std::vector<uint8>());
722 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest,
723 RobotRefreshSaveFailed) {
724 // Without the system salt, the robot token can't be stored.
725 RunTest();
726 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED);
729 } // namespace
730 } // namespace policy