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/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
;
59 using testing::Return
;
60 using testing::SaveArg
;
61 using testing::SetArgumentPointee
;
64 namespace em
= enterprise_management
;
69 void CopyLockResult(base::RunLoop
* loop
,
70 EnterpriseInstallAttributes::LockResult
* out
,
71 EnterpriseInstallAttributes::LockResult result
) {
76 class TestingDeviceCloudPolicyManagerChromeOS
77 : public DeviceCloudPolicyManagerChromeOS
{
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
{
92 DeviceCloudPolicyManagerChromeOSTest()
93 : fake_cryptohome_client_(new chromeos::FakeCryptohomeClient()),
94 state_keys_broker_(&fake_session_manager_client_
,
95 base::ThreadTaskRunnerHandle::Get()),
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_
= new DeviceCloudPolicyStoreChromeOS(
118 &device_settings_service_
, install_attributes_
.get(),
119 base::ThreadTaskRunnerHandle::Get());
120 manager_
.reset(new TestingDeviceCloudPolicyManagerChromeOS(
121 make_scoped_ptr(store_
), base::ThreadTaskRunnerHandle::Get(),
122 &state_keys_broker_
));
124 chrome::RegisterLocalState(local_state_
.registry());
125 manager_
->Init(&schema_registry_
);
127 // DeviceOAuth2TokenService uses the system request context to fetch
128 // OAuth tokens, then writes the token to local state, encrypting it
129 // first with methods in CryptohomeTokenEncryptor.
130 request_context_getter_
= new net::TestURLRequestContextGetter(
131 base::ThreadTaskRunnerHandle::Get());
132 TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
133 request_context_getter_
.get());
134 TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_
);
135 // SystemSaltGetter is used in DeviceOAuth2TokenService.
136 chromeos::SystemSaltGetter::Initialize();
137 chromeos::DeviceOAuth2TokenServiceFactory::Initialize();
138 url_fetcher_response_code_
= 200;
139 url_fetcher_response_string_
= "{\"access_token\":\"accessToken4Test\","
140 "\"expires_in\":1234,"
141 "\"refresh_token\":\"refreshToken4Test\"}";
143 AllowUninterestingRemoteCommandFetches();
146 void TearDown() override
{
147 manager_
->RemoveDeviceCloudPolicyManagerObserver(this);
148 manager_
->Shutdown();
150 initializer_
->Shutdown();
151 DeviceSettingsTestBase::TearDown();
153 chromeos::DeviceOAuth2TokenServiceFactory::Shutdown();
154 chromeos::SystemSaltGetter::Shutdown();
155 TestingBrowserProcess::GetGlobal()->SetLocalState(NULL
);
160 EnterpriseInstallAttributes::LockResult result
;
161 install_attributes_
->LockDevice(
162 PolicyBuilder::kFakeUsername
,
163 DEVICE_MODE_ENTERPRISE
,
164 PolicyBuilder::kFakeDeviceId
,
165 base::Bind(&CopyLockResult
, &loop
, &result
));
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_
, &device_management_service_
,
175 &consumer_device_management_service_
,
176 base::ThreadTaskRunnerHandle::Get(), install_attributes_
.get(),
177 &state_keys_broker_
, store_
, manager_
.get()));
178 initializer_
->Init();
181 void VerifyPolicyPopulated() {
183 bundle
.Get(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))
184 .Set(key::kDeviceMetricsReportingEnabled
,
185 POLICY_LEVEL_MANDATORY
,
186 POLICY_SCOPE_MACHINE
,
187 new base::FundamentalValue(false),
189 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
192 void AllowUninterestingRemoteCommandFetches() {
193 // We are not interested in remote command fetches that the client initiates
194 // automatically. Make them fail and ignore them otherwise.
195 EXPECT_CALL(device_management_service_
,
196 CreateJob(DeviceManagementRequestJob::TYPE_REMOTE_COMMANDS
, _
))
198 .WillRepeatedly(device_management_service_
.FailJob(
199 DM_STATUS_TEMPORARY_UNAVAILABLE
));
201 device_management_service_
,
202 StartJob(dm_protocol::kValueRequestRemoteCommands
, _
, _
, _
, _
, _
))
206 MOCK_METHOD0(OnDeviceCloudPolicyManagerConnected
, void());
207 MOCK_METHOD0(OnDeviceCloudPolicyManagerDisconnected
, void());
209 scoped_ptr
<EnterpriseInstallAttributes
> install_attributes_
;
211 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter_
;
212 net::TestURLFetcherFactory url_fetcher_factory_
;
213 int url_fetcher_response_code_
;
214 std::string url_fetcher_response_string_
;
215 TestingPrefServiceSimple local_state_
;
216 MockDeviceManagementService device_management_service_
;
217 MockDeviceManagementService consumer_device_management_service_
;
218 chromeos::ScopedTestDeviceSettingsService test_device_settings_service_
;
219 chromeos::ScopedTestCrosSettings test_cros_settings_
;
220 chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_
;
221 chromeos::FakeSessionManagerClient fake_session_manager_client_
;
222 chromeos::FakeCryptohomeClient
* fake_cryptohome_client_
;
223 ServerBackedStateKeysBroker state_keys_broker_
;
225 DeviceCloudPolicyStoreChromeOS
* store_
;
226 SchemaRegistry schema_registry_
;
227 scoped_ptr
<TestingDeviceCloudPolicyManagerChromeOS
> manager_
;
228 scoped_ptr
<DeviceCloudPolicyInitializer
> initializer_
;
231 DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSTest
);
234 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, FreshDevice
) {
235 owner_key_util_
->Clear();
236 FlushDeviceSettings();
237 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
239 manager_
->Initialize(&local_state_
);
242 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
245 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, EnrolledDevice
) {
247 FlushDeviceSettings();
248 EXPECT_EQ(CloudPolicyStore::STATUS_OK
, store_
->status());
249 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
250 VerifyPolicyPopulated();
252 // Trigger a policy refresh - this triggers a policy update.
253 MockDeviceManagementJob
* policy_fetch_job
= NULL
;
254 EXPECT_CALL(device_management_service_
,
255 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
257 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
258 EXPECT_CALL(device_management_service_
,
259 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
))
262 base::RunLoop().RunUntilIdle();
263 Mock::VerifyAndClearExpectations(&device_management_service_
);
264 ASSERT_TRUE(policy_fetch_job
);
265 // Should create a status uploader for reporting on enrolled devices.
266 EXPECT_TRUE(manager_
->GetStatusUploader());
267 VerifyPolicyPopulated();
269 manager_
->Shutdown();
270 VerifyPolicyPopulated();
272 EXPECT_EQ(store_
->policy()->service_account_identity(),
273 PolicyBuilder::kFakeServiceAccountIdentity
);
276 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, UnmanagedDevice
) {
277 device_policy_
.policy_data().set_state(em::PolicyData::UNMANAGED
);
278 device_policy_
.Build();
279 device_settings_test_helper_
.set_policy_blob(device_policy_
.GetBlob());
282 FlushDeviceSettings();
283 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
284 EXPECT_FALSE(store_
->is_managed());
286 // Policy settings should be ignored for UNMANAGED devices.
288 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
290 // Trigger a policy refresh.
291 MockDeviceManagementJob
* policy_fetch_job
= NULL
;
292 EXPECT_CALL(device_management_service_
,
293 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
295 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
296 EXPECT_CALL(device_management_service_
,
297 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
))
300 base::RunLoop().RunUntilIdle();
301 Mock::VerifyAndClearExpectations(&device_management_service_
);
302 ASSERT_TRUE(policy_fetch_job
);
303 // Should create a status provider for reporting on enrolled devices, even
304 // those that aren't managed.
305 EXPECT_TRUE(manager_
->GetStatusUploader());
307 // Switch back to ACTIVE, service the policy fetch and let it propagate.
308 device_policy_
.policy_data().set_state(em::PolicyData::ACTIVE
);
309 device_policy_
.Build();
310 device_settings_test_helper_
.set_policy_blob(device_policy_
.GetBlob());
311 em::DeviceManagementResponse policy_fetch_response
;
312 policy_fetch_response
.mutable_policy_response()->add_response()->CopyFrom(
313 device_policy_
.policy());
314 policy_fetch_job
->SendResponse(DM_STATUS_SUCCESS
, policy_fetch_response
);
315 FlushDeviceSettings();
317 // Policy state should now be active and the policy map should be populated.
318 EXPECT_TRUE(store_
->is_managed());
319 VerifyPolicyPopulated();
322 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, ConsumerDevice
) {
323 FlushDeviceSettings();
324 EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE
, store_
->status());
325 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
328 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
331 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
332 // Should not create a status provider for reporting on consumer devices.
333 EXPECT_FALSE(manager_
->GetStatusUploader());
335 manager_
->Shutdown();
336 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
339 TEST_F(DeviceCloudPolicyManagerChromeOSTest
, ConnectAndDisconnect
) {
341 FlushDeviceSettings();
342 EXPECT_FALSE(manager_
->core()->service()); // Not connected.
344 // Connect the manager.
345 MockDeviceManagementJob
* policy_fetch_job
= nullptr;
346 EXPECT_CALL(device_management_service_
,
347 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
348 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
349 EXPECT_CALL(device_management_service_
,
350 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
));
351 EXPECT_CALL(*this, OnDeviceCloudPolicyManagerConnected());
353 base::RunLoop().RunUntilIdle();
354 Mock::VerifyAndClearExpectations(&device_management_service_
);
355 Mock::VerifyAndClearExpectations(this);
356 EXPECT_TRUE(manager_
->core()->service()); // Connected.
358 // Disconnect the manager.
359 EXPECT_CALL(*this, OnDeviceCloudPolicyManagerDisconnected());
360 manager_
->Disconnect();
361 EXPECT_FALSE(manager_
->core()->service()); // Not connnected.
364 class DeviceCloudPolicyManagerChromeOSEnrollmentTest
365 : public DeviceCloudPolicyManagerChromeOSTest
{
367 void Done(EnrollmentStatus status
) {
372 MOCK_METHOD1(OnUnregistered
, void(bool));
375 DeviceCloudPolicyManagerChromeOSEnrollmentTest()
376 : management_mode_(MANAGEMENT_MODE_ENTERPRISE_MANAGED
),
377 register_status_(DM_STATUS_SUCCESS
),
378 policy_fetch_status_(DM_STATUS_SUCCESS
),
379 robot_auth_fetch_status_(DM_STATUS_SUCCESS
),
381 status_(EnrollmentStatus::ForStatus(EnrollmentStatus::STATUS_SUCCESS
)),
384 void SetUp() override
{
385 DeviceCloudPolicyManagerChromeOSTest::SetUp();
388 device_policy_
.SetDefaultNewSigningKey();
389 device_policy_
.policy_data().set_timestamp(
390 (base::Time::NowFromSystemTime() -
391 base::Time::UnixEpoch()).InMilliseconds());
392 device_policy_
.Build();
394 register_response_
.mutable_register_response()->set_device_management_token(
395 PolicyBuilder::kFakeToken
);
396 policy_fetch_response_
.mutable_policy_response()->add_response()->CopyFrom(
397 device_policy_
.policy());
398 robot_auth_fetch_response_
.mutable_service_api_access_response()
399 ->set_auth_code("auth_code_for_test");
400 loaded_blob_
= device_policy_
.GetBlob();
402 // Initialize the manager.
403 FlushDeviceSettings();
404 EXPECT_EQ(CloudPolicyStore::STATUS_BAD_STATE
, store_
->status());
405 EXPECT_TRUE(manager_
->IsInitializationComplete(POLICY_DOMAIN_CHROME
));
408 EXPECT_TRUE(manager_
->policies().Equals(bundle
));
413 void ExpectFailedEnrollment(EnrollmentStatus::Status status
) {
414 EXPECT_EQ(status
, status_
.status());
415 EXPECT_FALSE(store_
->is_managed());
416 PolicyBundle empty_bundle
;
417 EXPECT_TRUE(manager_
->policies().Equals(empty_bundle
));
420 void ExpectSuccessfulEnrollment() {
421 EXPECT_EQ(EnrollmentStatus::STATUS_SUCCESS
, status_
.status());
422 ASSERT_TRUE(manager_
->core()->client());
423 EXPECT_TRUE(manager_
->core()->client()->is_registered());
425 if (management_mode_
!= MANAGEMENT_MODE_CONSUMER_MANAGED
) {
426 EXPECT_EQ(DEVICE_MODE_ENTERPRISE
, install_attributes_
->GetMode());
427 EXPECT_TRUE(store_
->has_policy());
428 EXPECT_TRUE(store_
->is_managed());
429 VerifyPolicyPopulated();
434 // Trigger enrollment.
435 MockDeviceManagementJob
* register_job
= NULL
;
436 EXPECT_CALL(device_management_service_
,
437 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION
, _
))
439 .WillOnce(device_management_service_
.CreateAsyncJob(®ister_job
));
440 EXPECT_CALL(device_management_service_
,
441 StartJob(dm_protocol::kValueRequestRegister
, _
, _
, _
, _
, _
))
444 DoAll(SaveArg
<4>(&client_id_
), SaveArg
<5>(®ister_request_
)));
445 DeviceCloudPolicyInitializer::AllowedDeviceModes modes
;
446 modes
[DEVICE_MODE_ENTERPRISE
] = true;
448 chromeos::OwnerSettingsServiceChromeOS
* owner_settings_service
=
449 chromeos::OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(
451 ASSERT_TRUE(owner_settings_service
);
453 EnrollmentConfig enrollment_config
;
454 enrollment_config
.mode
= EnrollmentConfig::MODE_MANUAL
;
455 initializer_
->StartEnrollment(
456 management_mode_
, &device_management_service_
, owner_settings_service
,
457 enrollment_config
, "auth token", modes
,
458 base::Bind(&DeviceCloudPolicyManagerChromeOSEnrollmentTest::Done
,
459 base::Unretained(this)));
460 base::RunLoop().RunUntilIdle();
461 Mock::VerifyAndClearExpectations(&device_management_service_
);
462 AllowUninterestingRemoteCommandFetches();
467 // Process registration.
468 ASSERT_TRUE(register_job
);
469 MockDeviceManagementJob
* policy_fetch_job
= NULL
;
470 EXPECT_CALL(device_management_service_
,
471 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH
, _
))
473 .WillOnce(device_management_service_
.CreateAsyncJob(&policy_fetch_job
));
474 EXPECT_CALL(device_management_service_
,
475 StartJob(dm_protocol::kValueRequestPolicy
, _
, _
, _
, _
, _
))
477 register_job
->SendResponse(register_status_
, register_response_
);
478 Mock::VerifyAndClearExpectations(&device_management_service_
);
479 AllowUninterestingRemoteCommandFetches();
484 // Process policy fetch.
485 ASSERT_TRUE(policy_fetch_job
);
486 policy_fetch_job
->SendResponse(policy_fetch_status_
,
487 policy_fetch_response_
);
492 // Process verification.
493 MockDeviceManagementJob
* robot_auth_fetch_job
= NULL
;
494 EXPECT_CALL(device_management_service_
, CreateJob(
495 DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH
, _
))
497 .WillOnce(device_management_service_
.CreateAsyncJob(
498 &robot_auth_fetch_job
));
500 device_management_service_
,
501 StartJob(dm_protocol::kValueRequestApiAuthorization
, _
, _
, _
, _
, _
))
503 base::RunLoop().RunUntilIdle();
504 Mock::VerifyAndClearExpectations(&device_management_service_
);
505 AllowUninterestingRemoteCommandFetches();
510 // Process robot auth token fetch.
511 ASSERT_TRUE(robot_auth_fetch_job
);
512 robot_auth_fetch_job
->SendResponse(robot_auth_fetch_status_
,
513 robot_auth_fetch_response_
);
514 Mock::VerifyAndClearExpectations(&device_management_service_
);
515 AllowUninterestingRemoteCommandFetches();
520 // Process robot refresh token fetch if the auth code fetch succeeded.
521 // DeviceCloudPolicyInitializer holds an EnrollmentHandlerChromeOS which
522 // holds a GaiaOAuthClient that fetches the refresh token during enrollment.
523 // We return a successful OAuth response via a TestURLFetcher to trigger the
524 // happy path for these classes so that enrollment can continue.
525 if (robot_auth_fetch_status_
== DM_STATUS_SUCCESS
) {
526 net::TestURLFetcher
* url_fetcher
= url_fetcher_factory_
.GetFetcherByID(
527 gaia::GaiaOAuthClient::kUrlFetcherId
);
528 ASSERT_TRUE(url_fetcher
);
529 url_fetcher
->SetMaxRetriesOn5xx(0);
530 url_fetcher
->set_status(net::URLRequestStatus());
531 url_fetcher
->set_response_code(url_fetcher_response_code_
);
532 url_fetcher
->SetResponseString(url_fetcher_response_string_
);
533 url_fetcher
->delegate()->OnURLFetchComplete(url_fetcher
);
536 if (management_mode_
== MANAGEMENT_MODE_CONSUMER_MANAGED
)
537 FlushDeviceSettings();
539 base::RunLoop().RunUntilIdle();
544 // Process robot refresh token store.
545 chromeos::DeviceOAuth2TokenService
* token_service
=
546 chromeos::DeviceOAuth2TokenServiceFactory::Get();
547 EXPECT_TRUE(token_service
->RefreshTokenIsAvailable(
548 token_service
->GetRobotAccountId()));
550 // Process policy store.
551 device_settings_test_helper_
.set_store_result(store_result_
);
552 device_settings_test_helper_
.FlushStore();
553 EXPECT_EQ(device_policy_
.GetBlob(),
554 device_settings_test_helper_
.policy_blob());
559 // Key installation and policy load.
560 device_settings_test_helper_
.set_policy_blob(loaded_blob_
);
561 owner_key_util_
->SetPublicKeyFromPrivateKey(
562 *device_policy_
.GetNewSigningKey());
563 ReloadDeviceSettings();
566 ManagementMode management_mode_
;
568 DeviceManagementStatus register_status_
;
569 em::DeviceManagementResponse register_response_
;
571 DeviceManagementStatus policy_fetch_status_
;
572 em::DeviceManagementResponse policy_fetch_response_
;
574 DeviceManagementStatus robot_auth_fetch_status_
;
575 em::DeviceManagementResponse robot_auth_fetch_response_
;
578 std::string loaded_blob_
;
580 em::DeviceManagementRequest register_request_
;
581 std::string client_id_
;
582 EnrollmentStatus status_
;
587 DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSEnrollmentTest
);
590 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, Success
) {
592 ExpectSuccessfulEnrollment();
595 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, Reenrollment
) {
599 ExpectSuccessfulEnrollment();
600 EXPECT_TRUE(register_request_
.register_request().reregister());
601 EXPECT_EQ(PolicyBuilder::kFakeDeviceId
, client_id_
);
604 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, RegistrationFailed
) {
605 register_status_
= DM_STATUS_REQUEST_FAILED
;
607 ExpectFailedEnrollment(EnrollmentStatus::STATUS_REGISTRATION_FAILED
);
608 EXPECT_EQ(DM_STATUS_REQUEST_FAILED
, status_
.client_status());
611 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
612 RobotAuthCodeFetchFailed
) {
613 robot_auth_fetch_status_
= DM_STATUS_REQUEST_FAILED
;
615 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_AUTH_FETCH_FAILED
);
618 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
619 RobotRefreshTokenFetchResponseCodeFailed
) {
620 url_fetcher_response_code_
= 400;
622 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED
);
623 EXPECT_EQ(400, status_
.http_status());
626 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
627 RobotRefreshTokenFetchResponseStringFailed
) {
628 url_fetcher_response_string_
= "invalid response json";
630 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_FETCH_FAILED
);
633 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
634 RobotRefreshEncryptionFailed
) {
635 // The encryption lib is a noop for tests, but empty results from encryption
636 // is an error, so we simulate an encryption error by returning an empty
638 url_fetcher_response_string_
= "{\"access_token\":\"accessToken4Test\","
639 "\"expires_in\":1234,"
640 "\"refresh_token\":\"\"}";
642 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED
);
645 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, PolicyFetchFailed
) {
646 policy_fetch_status_
= DM_STATUS_REQUEST_FAILED
;
648 ExpectFailedEnrollment(EnrollmentStatus::STATUS_POLICY_FETCH_FAILED
);
649 EXPECT_EQ(DM_STATUS_REQUEST_FAILED
, status_
.client_status());
652 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, ValidationFailed
) {
653 device_policy_
.policy().set_policy_data_signature("bad");
654 policy_fetch_response_
.clear_policy_response();
655 policy_fetch_response_
.mutable_policy_response()->add_response()->CopyFrom(
656 device_policy_
.policy());
658 ExpectFailedEnrollment(EnrollmentStatus::STATUS_VALIDATION_FAILED
);
659 EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_BAD_INITIAL_SIGNATURE
,
660 status_
.validation_status());
663 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, StoreError
) {
664 store_result_
= false;
666 ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR
);
667 EXPECT_EQ(CloudPolicyStore::STATUS_STORE_ERROR
,
668 status_
.store_status());
671 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, LoadError
) {
672 loaded_blob_
.clear();
674 ExpectFailedEnrollment(EnrollmentStatus::STATUS_STORE_ERROR
);
675 EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR
,
676 status_
.store_status());
679 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
,
680 SuccessfulConsumerManagementEnrollment
) {
681 management_mode_
= MANAGEMENT_MODE_CONSUMER_MANAGED
;
682 owner_key_util_
->SetPrivateKey(device_policy_
.GetNewSigningKey());
683 InitOwner(device_policy_
.policy_data().username(), true);
684 FlushDeviceSettings();
686 device_policy_
.policy_data().set_management_mode(em::PolicyData::LOCAL_OWNER
);
687 device_policy_
.Build();
688 device_settings_test_helper_
.set_policy_blob(device_policy_
.GetBlob());
689 ReloadDeviceSettings();
692 ExpectSuccessfulEnrollment();
695 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, UnregisterSucceeds
) {
698 ExpectSuccessfulEnrollment();
700 // Set up mock objects for the upcoming unregistration job.
701 em::DeviceManagementResponse response
;
702 response
.mutable_unregister_response();
703 EXPECT_CALL(device_management_service_
,
704 CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION
, _
))
705 .WillOnce(device_management_service_
.SucceedJob(response
));
706 EXPECT_CALL(device_management_service_
, StartJob(_
, _
, _
, _
, _
, _
));
707 EXPECT_CALL(*this, OnUnregistered(true));
709 // Start unregistering.
710 manager_
->Unregister(base::Bind(
711 &DeviceCloudPolicyManagerChromeOSEnrollmentTest::OnUnregistered
,
712 base::Unretained(this)));
715 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentTest
, UnregisterFails
) {
718 ExpectSuccessfulEnrollment();
720 // Set up mock objects for the upcoming unregistration job.
721 EXPECT_CALL(device_management_service_
,
722 CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION
, _
))
723 .WillOnce(device_management_service_
.FailJob(DM_STATUS_REQUEST_FAILED
));
724 EXPECT_CALL(device_management_service_
, StartJob(_
, _
, _
, _
, _
, _
));
725 EXPECT_CALL(*this, OnUnregistered(false));
727 // Start unregistering.
728 manager_
->Unregister(base::Bind(
729 &DeviceCloudPolicyManagerChromeOSEnrollmentTest::OnUnregistered
,
730 base::Unretained(this)));
733 // A subclass that runs with a blank system salt.
734 class DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest
735 : public DeviceCloudPolicyManagerChromeOSEnrollmentTest
{
737 DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest() {
738 // Set up a FakeCryptohomeClient with a blank system salt.
739 fake_cryptohome_client_
->set_system_salt(std::vector
<uint8
>());
743 TEST_F(DeviceCloudPolicyManagerChromeOSEnrollmentBlankSystemSaltTest
,
744 RobotRefreshSaveFailed
) {
745 // Without the system salt, the robot token can't be stored.
747 ExpectFailedEnrollment(EnrollmentStatus::STATUS_ROBOT_REFRESH_STORE_FAILED
);
751 } // namespace policy