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"
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/prefs/pref_registry_simple.h"
15 #include "base/prefs/testing_pref_service.h"
16 #include "base/run_loop.h"
17 #include "base/thread_task_runner_handle.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/policy_types.h"
47 #include "components/policy/core/common/schema_registry.h"
48 #include "google_apis/gaia/gaia_oauth_client.h"
49 #include "net/url_request/test_url_fetcher_factory.h"
50 #include "net/url_request/url_request_test_util.h"
51 #include "policy/policy_constants.h"
52 #include "policy/proto/device_management_backend.pb.h"
53 #include "testing/gmock/include/gmock/gmock.h"
54 #include "testing/gtest/include/gtest/gtest.h"
56 using testing::AnyNumber
;
57 using testing::AtMost
;
60 using testing::Return
;
61 using testing::SaveArg
;
62 using testing::SetArgumentPointee
;
65 namespace em
= enterprise_management
;
70 void CopyLockResult(base::RunLoop
* loop
,
71 EnterpriseInstallAttributes::LockResult
* out
,
72 EnterpriseInstallAttributes::LockResult result
) {
77 class TestingDeviceCloudPolicyManagerChromeOS
78 : public DeviceCloudPolicyManagerChromeOS
{
80 TestingDeviceCloudPolicyManagerChromeOS(
81 scoped_ptr
<DeviceCloudPolicyStoreChromeOS
> store
,
82 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
83 ServerBackedStateKeysBroker
* state_keys_broker
)
84 : DeviceCloudPolicyManagerChromeOS(
85 store
.Pass(), task_runner
, state_keys_broker
) {}
86 ~TestingDeviceCloudPolicyManagerChromeOS() override
{}
89 class DeviceCloudPolicyManagerChromeOSTest
90 : public chromeos::DeviceSettingsTestBase
,
91 public DeviceCloudPolicyManagerChromeOS::Observer
{
93 DeviceCloudPolicyManagerChromeOSTest()
94 : fake_cryptohome_client_(new chromeos::FakeCryptohomeClient()),
95 state_keys_broker_(&fake_session_manager_client_
,
96 base::ThreadTaskRunnerHandle::Get()),
98 fake_statistics_provider_
.SetMachineStatistic("serial_numer", "test_sn");
99 std::vector
<std::string
> state_keys
;
100 state_keys
.push_back("1");
101 state_keys
.push_back("2");
102 state_keys
.push_back("3");
103 fake_session_manager_client_
.set_server_backed_state_keys(state_keys
);
106 ~DeviceCloudPolicyManagerChromeOSTest() override
{
107 chromeos::system::StatisticsProvider::SetTestProvider(NULL
);
110 void SetUp() override
{
111 DeviceSettingsTestBase::SetUp();
113 dbus_setter_
->SetCryptohomeClient(
114 scoped_ptr
<chromeos::CryptohomeClient
>(fake_cryptohome_client_
));
116 install_attributes_
.reset(
117 new EnterpriseInstallAttributes(fake_cryptohome_client_
));
118 store_
= new DeviceCloudPolicyStoreChromeOS(
119 &device_settings_service_
, install_attributes_
.get(),
120 base::ThreadTaskRunnerHandle::Get());
121 manager_
.reset(new TestingDeviceCloudPolicyManagerChromeOS(
122 make_scoped_ptr(store_
), base::ThreadTaskRunnerHandle::Get(),
123 &state_keys_broker_
));
125 chrome::RegisterLocalState(local_state_
.registry());
126 manager_
->Init(&schema_registry_
);
128 // DeviceOAuth2TokenService uses the system request context to fetch
129 // OAuth tokens, then writes the token to local state, encrypting it
130 // first with methods in CryptohomeTokenEncryptor.
131 request_context_getter_
= new net::TestURLRequestContextGetter(
132 base::ThreadTaskRunnerHandle::Get());
133 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
134 request_context_getter_
.get());
135 TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_
);
136 // SystemSaltGetter is used in DeviceOAuth2TokenService.
137 chromeos::SystemSaltGetter::Initialize();
138 chromeos::DeviceOAuth2TokenServiceFactory::Initialize();
139 url_fetcher_response_code_
= 200;
140 url_fetcher_response_string_
= "{\"access_token\":\"accessToken4Test\","
141 "\"expires_in\":1234,"
142 "\"refresh_token\":\"refreshToken4Test\"}";
144 AllowUninterestingRemoteCommandFetches();
147 void TearDown() override
{
148 manager_
->RemoveDeviceCloudPolicyManagerObserver(this);
149 manager_
->Shutdown();
151 initializer_
->Shutdown();
152 DeviceSettingsTestBase::TearDown();
154 chromeos::DeviceOAuth2TokenServiceFactory::Shutdown();
155 chromeos::SystemSaltGetter::Shutdown();
156 TestingBrowserProcess::GetGlobal()->SetLocalState(NULL
);
161 EnterpriseInstallAttributes::LockResult result
;
162 install_attributes_
->LockDevice(
163 PolicyBuilder::kFakeUsername
,
164 DEVICE_MODE_ENTERPRISE
,
165 PolicyBuilder::kFakeDeviceId
,
166 base::Bind(&CopyLockResult
, &loop
, &result
));
168 ASSERT_EQ(EnterpriseInstallAttributes::LOCK_SUCCESS
, result
);
171 void ConnectManager() {
172 manager_
->Initialize(&local_state_
);
173 manager_
->AddDeviceCloudPolicyManagerObserver(this);
174 initializer_
.reset(new DeviceCloudPolicyInitializer(
175 &local_state_
, &device_management_service_
,
176 &consumer_device_management_service_
,
177 base::ThreadTaskRunnerHandle::Get(), install_attributes_
.get(),
178 &state_keys_broker_
, store_
, manager_
.get()));
179 initializer_
->Init();
182 void VerifyPolicyPopulated() {
184 bundle
.Get(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))
185 .Set(key::kDeviceMetricsReportingEnabled
,
186 POLICY_LEVEL_MANDATORY
,
187 POLICY_SCOPE_MACHINE
,
189 new base::FundamentalValue(false),
191 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
194 void AllowUninterestingRemoteCommandFetches() {
195 // We are not interested in remote command fetches that the client initiates
196 // automatically. Make them fail and ignore them otherwise.
197 EXPECT_CALL(device_management_service_
,
198 CreateJob(DeviceManagementRequestJob::TYPE_REMOTE_COMMANDS
, _
))
200 .WillRepeatedly(device_management_service_
.FailJob(
201 DM_STATUS_TEMPORARY_UNAVAILABLE
));
203 device_management_service_
,
204 StartJob(dm_protocol::kValueRequestRemoteCommands
, _
, _
, _
, _
, _
))
208 MOCK_METHOD0(OnDeviceCloudPolicyManagerConnected
, void());
209 MOCK_METHOD0(OnDeviceCloudPolicyManagerDisconnected
, void());
211 scoped_ptr
<EnterpriseInstallAttributes
> install_attributes_
;
213 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter_
;
214 net::TestURLFetcherFactory url_fetcher_factory_
;
215 int url_fetcher_response_code_
;
216 std::string url_fetcher_response_string_
;
217 TestingPrefServiceSimple local_state_
;
218 MockDeviceManagementService device_management_service_
;
219 MockDeviceManagementService consumer_device_management_service_
;
220 chromeos::ScopedTestDeviceSettingsService test_device_settings_service_
;
221 chromeos::ScopedTestCrosSettings test_cros_settings_
;
222 chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_
;
223 chromeos::FakeSessionManagerClient fake_session_manager_client_
;
224 chromeos::FakeCryptohomeClient
* fake_cryptohome_client_
;
225 ServerBackedStateKeysBroker state_keys_broker_
;
227 DeviceCloudPolicyStoreChromeOS
* store_
;
228 SchemaRegistry schema_registry_
;
229 scoped_ptr
<TestingDeviceCloudPolicyManagerChromeOS
> manager_
;
230 scoped_ptr
<DeviceCloudPolicyInitializer
> initializer_
;
233 DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSTest
);
236 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, FreshDevice
) {
237 owner_key_util_
->Clear();
238 FlushDeviceSettings();
239 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
241 manager_
->Initialize(&local_state_
);
244 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
247 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, EnrolledDevice
) {
249 FlushDeviceSettings();
250 EXPECT_EQ(CloudPolicyStore::STATUS_OK
, store_
->status());
251 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
252 VerifyPolicyPopulated();
254 // Trigger a policy refresh - this triggers a policy update.
255 MockDeviceManagementJob
* policy_fetch_job
= NULL
;
256 EXPECT_CALL(device_management_service_
,
257 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
259 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
260 EXPECT_CALL(device_management_service_
,
261 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
))
264 base::RunLoop().RunUntilIdle();
265 Mock::VerifyAndClearExpectations(&device_management_service_
);
266 ASSERT_TRUE(policy_fetch_job
);
267 // Should create a status uploader for reporting on enrolled devices.
268 EXPECT_TRUE(manager_
->GetStatusUploader());
269 VerifyPolicyPopulated();
271 manager_
->Shutdown();
272 VerifyPolicyPopulated();
274 EXPECT_EQ(store_
->policy()->service_account_identity(),
275 PolicyBuilder::kFakeServiceAccountIdentity
);
278 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, UnmanagedDevice
) {
279 device_policy_
.policy_data().set_state(em::PolicyData::UNMANAGED
);
280 device_policy_
.Build();
281 device_settings_test_helper_
.set_policy_blob(device_policy_
.GetBlob());
284 FlushDeviceSettings();
285 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
286 EXPECT_FALSE(store_
->is_managed());
288 // Policy settings should be ignored for UNMANAGED devices.
290 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
292 // Trigger a policy refresh.
293 MockDeviceManagementJob
* policy_fetch_job
= NULL
;
294 EXPECT_CALL(device_management_service_
,
295 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
297 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
298 EXPECT_CALL(device_management_service_
,
299 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
))
302 base::RunLoop().RunUntilIdle();
303 Mock::VerifyAndClearExpectations(&device_management_service_
);
304 ASSERT_TRUE(policy_fetch_job
);
305 // Should create a status provider for reporting on enrolled devices, even
306 // those that aren't managed.
307 EXPECT_TRUE(manager_
->GetStatusUploader());
309 // Switch back to ACTIVE, service the policy fetch and let it propagate.
310 device_policy_
.policy_data().set_state(em::PolicyData::ACTIVE
);
311 device_policy_
.Build();
312 device_settings_test_helper_
.set_policy_blob(device_policy_
.GetBlob());
313 em::DeviceManagementResponse policy_fetch_response
;
314 policy_fetch_response
.mutable_policy_response()->add_response()->CopyFrom(
315 device_policy_
.policy());
316 policy_fetch_job
->SendResponse(DM_STATUS_SUCCESS
, policy_fetch_response
);
317 FlushDeviceSettings();
319 // Policy state should now be active and the policy map should be populated.
320 EXPECT_TRUE(store_
->is_managed());
321 VerifyPolicyPopulated();
324 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, ConsumerDevice
) {
325 FlushDeviceSettings();
326 EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE
, store_
->status());
327 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
330 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
333 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
334 // Should not create a status provider for reporting on consumer devices.
335 EXPECT_FALSE(manager_
->GetStatusUploader());
337 manager_
->Shutdown();
338 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
341 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, ConnectAndDisconnect
) {
343 FlushDeviceSettings();
344 EXPECT_FALSE(manager_
->core()->service()); // Not connected.
346 // Connect the manager.
347 MockDeviceManagementJob
* policy_fetch_job
= nullptr;
348 EXPECT_CALL(device_management_service_
,
349 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
350 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
351 EXPECT_CALL(device_management_service_
,
352 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
));
353 EXPECT_CALL(*this, OnDeviceCloudPolicyManagerConnected());
355 base::RunLoop().RunUntilIdle();
356 Mock::VerifyAndClearExpectations(&device_management_service_
);
357 Mock::VerifyAndClearExpectations(this);
358 EXPECT_TRUE(manager_
->core()->service()); // Connected.
360 // Disconnect the manager.
361 EXPECT_CALL(*this, OnDeviceCloudPolicyManagerDisconnected());
362 manager_
->Disconnect();
363 EXPECT_FALSE(manager_
->core()->service()); // Not connnected.
366 class DeviceCloudPolicyManagerChromeOSEnrollmentTest
367 : public DeviceCloudPolicyManagerChromeOSTest
{
369 void Done(EnrollmentStatus status
) {
374 MOCK_METHOD1(OnUnregistered
, void(bool));
377 DeviceCloudPolicyManagerChromeOSEnrollmentTest()
378 : management_mode_(MANAGEMENT_MODE_ENTERPRISE_MANAGED
),
379 register_status_(DM_STATUS_SUCCESS
),
380 policy_fetch_status_(DM_STATUS_SUCCESS
),
381 robot_auth_fetch_status_(DM_STATUS_SUCCESS
),
383 status_(EnrollmentStatus::ForStatus(EnrollmentStatus::STATUS_SUCCESS
)),
386 void SetUp() override
{
387 DeviceCloudPolicyManagerChromeOSTest::SetUp();
390 device_policy_
.SetDefaultNewSigningKey();
391 device_policy_
.policy_data().set_timestamp(
392 (base::Time::NowFromSystemTime() -
393 base::Time::UnixEpoch()).InMilliseconds());
394 device_policy_
.Build();
396 register_response_
.mutable_register_response()->set_device_management_token(
397 PolicyBuilder::kFakeToken
);
398 policy_fetch_response_
.mutable_policy_response()->add_response()->CopyFrom(
399 device_policy_
.policy());
400 robot_auth_fetch_response_
.mutable_service_api_access_response()
401 ->set_auth_code("auth_code_for_test");
402 loaded_blob_
= device_policy_
.GetBlob();
404 // Initialize the manager.
405 FlushDeviceSettings();
406 EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE
, store_
->status());
407 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
410 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
415 void ExpectFailedEnrollment(EnrollmentStatus::Status status
) {
416 EXPECT_EQ(status
, status_
.status());
417 EXPECT_FALSE(store_
->is_managed());
418 PolicyBundle empty_bundle
;
419 EXPECT_TRUE(manager_
->policies().Equals(empty_bundle
));
422 void ExpectSuccessfulEnrollment() {
423 EXPECT_EQ(EnrollmentStatus::STATUS_SUCCESS
, status_
.status());
424 ASSERT_TRUE(manager_
->core()->client());
425 EXPECT_TRUE(manager_
->core()->client()->is_registered());
427 if (management_mode_
!= MANAGEMENT_MODE_CONSUMER_MANAGED
) {
428 EXPECT_EQ(DEVICE_MODE_ENTERPRISE
, install_attributes_
->GetMode());
429 EXPECT_TRUE(store_
->has_policy());
430 EXPECT_TRUE(store_
->is_managed());
431 VerifyPolicyPopulated();
436 // Trigger enrollment.
437 MockDeviceManagementJob
* register_job
= NULL
;
438 EXPECT_CALL(device_management_service_
,
439 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION
, _
))
441 .WillOnce(device_management_service_
.CreateAsyncJob(®ister_job
));
442 EXPECT_CALL(device_management_service_
,
443 StartJob(dm_protocol::kValueRequestRegister
, _
, _
, _
, _
, _
))
446 DoAll(SaveArg
<4>(&client_id_
), SaveArg
<5>(®ister_request_
)));
447 DeviceCloudPolicyInitializer::AllowedDeviceModes modes
;
448 modes
[DEVICE_MODE_ENTERPRISE
] = true;
450 chromeos::OwnerSettingsServiceChromeOS
* owner_settings_service
=
451 chromeos::OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(
453 ASSERT_TRUE(owner_settings_service
);
455 EnrollmentConfig enrollment_config
;
456 enrollment_config
.mode
= EnrollmentConfig::MODE_MANUAL
;
457 initializer_
->StartEnrollment(
458 management_mode_
, &device_management_service_
, owner_settings_service
,
459 enrollment_config
, "auth token", modes
,
460 base::Bind(&DeviceCloudPolicyManagerChromeOSEnrollmentTest::Done
,
461 base::Unretained(this)));
462 base::RunLoop().RunUntilIdle();
463 Mock::VerifyAndClearExpectations(&device_management_service_
);
464 AllowUninterestingRemoteCommandFetches();
469 // Process registration.
470 ASSERT_TRUE(register_job
);
471 MockDeviceManagementJob
* policy_fetch_job
= NULL
;
472 EXPECT_CALL(device_management_service_
,
473 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
475 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
476 EXPECT_CALL(device_management_service_
,
477 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
))
479 register_job
->SendResponse(register_status_
, register_response_
);
480 Mock::VerifyAndClearExpectations(&device_management_service_
);
481 AllowUninterestingRemoteCommandFetches();
486 // Process policy fetch.
487 ASSERT_TRUE(policy_fetch_job
);
488 policy_fetch_job
->SendResponse(policy_fetch_status_
,
489 policy_fetch_response_
);
494 // Process verification.
495 MockDeviceManagementJob
* robot_auth_fetch_job
= NULL
;
496 EXPECT_CALL(device_management_service_
, CreateJob(
497 DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH
, _
))
499 .WillOnce(device_management_service_
.CreateAsyncJob(
500 &robot_auth_fetch_job
));
502 device_management_service_
,
503 StartJob(dm_protocol::kValueRequestApiAuthorization
, _
, _
, _
, _
, _
))
505 base::RunLoop().RunUntilIdle();
506 Mock::VerifyAndClearExpectations(&device_management_service_
);
507 AllowUninterestingRemoteCommandFetches();
512 // Process robot auth token fetch.
513 ASSERT_TRUE(robot_auth_fetch_job
);
514 robot_auth_fetch_job
->SendResponse(robot_auth_fetch_status_
,
515 robot_auth_fetch_response_
);
516 Mock::VerifyAndClearExpectations(&device_management_service_
);
517 AllowUninterestingRemoteCommandFetches();
522 // Process robot refresh token fetch if the auth code fetch succeeded.
523 // DeviceCloudPolicyInitializer holds an EnrollmentHandlerChromeOS which
524 // holds a GaiaOAuthClient that fetches the refresh token during enrollment.
525 // We return a successful OAuth response via a TestURLFetcher to trigger the
526 // happy path for these classes so that enrollment can continue.
527 if (robot_auth_fetch_status_
== DM_STATUS_SUCCESS
) {
528 net::TestURLFetcher
* url_fetcher
= url_fetcher_factory_
.GetFetcherByID(
529 gaia::GaiaOAuthClient::kUrlFetcherId
);
530 ASSERT_TRUE(url_fetcher
);
531 url_fetcher
->SetMaxRetriesOn5xx(0);
532 url_fetcher
->set_status(net::URLRequestStatus());
533 url_fetcher
->set_response_code(url_fetcher_response_code_
);
534 url_fetcher
->SetResponseString(url_fetcher_response_string_
);
535 url_fetcher
->delegate()->OnURLFetchComplete(url_fetcher
);
538 if (management_mode_
== MANAGEMENT_MODE_CONSUMER_MANAGED
)
539 FlushDeviceSettings();
541 base::RunLoop().RunUntilIdle();
546 // Process robot refresh token store.
547 chromeos::DeviceOAuth2TokenService
* token_service
=
548 chromeos::DeviceOAuth2TokenServiceFactory::Get();
549 EXPECT_TRUE(token_service
->RefreshTokenIsAvailable(
550 token_service
->GetRobotAccountId()));
552 // Process policy store.
553 device_settings_test_helper_
.set_store_result(store_result_
);
554 device_settings_test_helper_
.FlushStore();
555 EXPECT_EQ(device_policy_
.GetBlob(),
556 device_settings_test_helper_
.policy_blob());
561 // Key installation and policy load.
562 device_settings_test_helper_
.set_policy_blob(loaded_blob_
);
563 owner_key_util_
->SetPublicKeyFromPrivateKey(
564 *device_policy_
.GetNewSigningKey());
565 ReloadDeviceSettings();
568 ManagementMode management_mode_
;
570 DeviceManagementStatus register_status_
;
571 em::DeviceManagementResponse register_response_
;
573 DeviceManagementStatus policy_fetch_status_
;
574 em::DeviceManagementResponse policy_fetch_response_
;
576 DeviceManagementStatus robot_auth_fetch_status_
;
577 em::DeviceManagementResponse robot_auth_fetch_response_
;
580 std::string loaded_blob_
;
582 em::DeviceManagementRequest register_request_
;
583 std::string client_id_
;
584 EnrollmentStatus status_
;
589 DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSEnrollmentTest
);
592 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, Success
) {
594 ExpectSuccessfulEnrollment();
597 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, Reenrollment
) {
601 ExpectSuccessfulEnrollment();
602 EXPECT_TRUE(register_request_
.register_request().reregister());
603 EXPECT_EQ(PolicyBuilder::kFakeDeviceId
, client_id_
);
606 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, RegistrationFailed
) {
607 register_status_
= DM_STATUS_REQUEST_FAILED
;
609 ExpectFailedEnrollment(EnrollmentStatus::STATUS_REGISTRATION_FAILED
);
610 EXPECT_EQ(DM_STATUS_REQUEST_FAILED
, status_
.client_status());
613 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
614 RobotAuthCodeFetchFailed
) {
615 robot_auth_fetch_status_
= DM_STATUS_REQUEST_FAILED
;
617 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_AUTH_FETCH_FAILED
);
620 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
621 RobotRefreshTokenFetchResponseCodeFailed
) {
622 url_fetcher_response_code_
= 400;
624 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED
);
625 EXPECT_EQ(400, status_
.http_status());
628 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
629 RobotRefreshTokenFetchResponseStringFailed
) {
630 url_fetcher_response_string_
= "invalid response json";
632 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED
);
635 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
636 RobotRefreshEncryptionFailed
) {
637 // The encryption lib is a noop for tests, but empty results from encryption
638 // is an error, so we simulate an encryption error by returning an empty
640 url_fetcher_response_string_
= "{\"access_token\":\"accessToken4Test\","
641 "\"expires_in\":1234,"
642 "\"refresh_token\":\"\"}";
644 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED
);
647 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, PolicyFetchFailed
) {
648 policy_fetch_status_
= DM_STATUS_REQUEST_FAILED
;
650 ExpectFailedEnrollment(EnrollmentStatus::STATUS_POLICY_FETCH_FAILED
);
651 EXPECT_EQ(DM_STATUS_REQUEST_FAILED
, status_
.client_status());
654 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, ValidationFailed
) {
655 device_policy_
.policy().set_policy_data_signature("bad");
656 policy_fetch_response_
.clear_policy_response();
657 policy_fetch_response_
.mutable_policy_response()->add_response()->CopyFrom(
658 device_policy_
.policy());
660 ExpectFailedEnrollment(EnrollmentStatus::STATUS_VALIDATION_FAILED
);
661 EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_BAD_INITIAL_SIGNATURE
,
662 status_
.validation_status());
665 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, StoreError
) {
666 store_result_
= false;
668 ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR
);
669 EXPECT_EQ(CloudPolicyStore::STATUS_STORE_ERROR
,
670 status_
.store_status());
673 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, LoadError
) {
674 loaded_blob_
.clear();
676 ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR
);
677 EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR
,
678 status_
.store_status());
681 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
682 SuccessfulConsumerManagementEnrollment
) {
683 management_mode_
= MANAGEMENT_MODE_CONSUMER_MANAGED
;
684 owner_key_util_
->SetPrivateKey(device_policy_
.GetNewSigningKey());
685 InitOwner(device_policy_
.policy_data().username(), true);
686 FlushDeviceSettings();
688 device_policy_
.policy_data().set_management_mode(em::PolicyData::LOCAL_OWNER
);
689 device_policy_
.Build();
690 device_settings_test_helper_
.set_policy_blob(device_policy_
.GetBlob());
691 ReloadDeviceSettings();
694 ExpectSuccessfulEnrollment();
697 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, UnregisterSucceeds
) {
700 ExpectSuccessfulEnrollment();
702 // Set up mock objects for the upcoming unregistration job.
703 em::DeviceManagementResponse response
;
704 response
.mutable_unregister_response();
705 EXPECT_CALL(device_management_service_
,
706 CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION
, _
))
707 .WillOnce(device_management_service_
.SucceedJob(response
));
708 EXPECT_CALL(device_management_service_
, StartJob(_
, _
, _
, _
, _
, _
));
709 EXPECT_CALL(*this, OnUnregistered(true));
711 // Start unregistering.
712 manager_
->Unregister(base::Bind(
713 &DeviceCloudPolicyManagerChromeOSEnrollmentTest::OnUnregistered
,
714 base::Unretained(this)));
717 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, UnregisterFails
) {
720 ExpectSuccessfulEnrollment();
722 // Set up mock objects for the upcoming unregistration job.
723 EXPECT_CALL(device_management_service_
,
724 CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION
, _
))
725 .WillOnce(device_management_service_
.FailJob(DM_STATUS_REQUEST_FAILED
));
726 EXPECT_CALL(device_management_service_
, StartJob(_
, _
, _
, _
, _
, _
));
727 EXPECT_CALL(*this, OnUnregistered(false));
729 // Start unregistering.
730 manager_
->Unregister(base::Bind(
731 &DeviceCloudPolicyManagerChromeOSEnrollmentTest::OnUnregistered
,
732 base::Unretained(this)));
735 // A subclass that runs with a blank system salt.
736 class DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest
737 : public DeviceCloudPolicyManagerChromeOSEnrollmentTest
{
739 DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest() {
740 // Set up a FakeCryptohomeClient with a blank system salt.
741 fake_cryptohome_client_
->set_system_salt(std::vector
<uint8
>());
745 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest
,
746 RobotRefreshSaveFailed
) {
747 // Without the system salt, the robot token can't be stored.
749 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED
);
753 } // namespace policy