device_local_account_policy_service_unittest.cc revision 8bcbed890bc3ce4d7a057a8f32cab53fa534672e
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_local_account_policy_service.h"
6
7#include "base/bind.h"
8#include "base/bind_helpers.h"
9#include "base/callback.h"
10#include "base/file_util.h"
11#include "base/files/file_path.h"
12#include "base/files/scoped_temp_dir.h"
13#include "base/message_loop/message_loop.h"
14#include "base/message_loop/message_loop_proxy.h"
15#include "base/path_service.h"
16#include "base/run_loop.h"
17#include "base/strings/string_number_conversions.h"
18#include "base/strings/stringprintf.h"
19#include "base/test/scoped_path_override.h"
20#include "base/test/test_simple_task_runner.h"
21#include "chrome/browser/chromeos/policy/device_local_account.h"
22#include "chrome/browser/chromeos/policy/device_local_account_policy_provider.h"
23#include "chrome/browser/chromeos/settings/cros_settings.h"
24#include "chrome/browser/chromeos/settings/device_settings_service.h"
25#include "chrome/browser/chromeos/settings/device_settings_test_helper.h"
26#include "chrome/browser/policy/cloud/cloud_policy_client.h"
27#include "chrome/browser/policy/cloud/cloud_policy_constants.h"
28#include "chrome/browser/policy/cloud/cloud_policy_service.h"
29#include "chrome/browser/policy/cloud/mock_device_management_service.h"
30#include "chrome/browser/policy/cloud/policy_builder.h"
31#include "chrome/browser/policy/external_data_fetcher.h"
32#include "chrome/browser/policy/mock_configuration_policy_provider.h"
33#include "chrome/browser/policy/proto/chromeos/chrome_device_policy.pb.h"
34#include "chrome/common/chrome_paths.h"
35#include "chromeos/chromeos_paths.h"
36#include "chromeos/dbus/power_policy_controller.h"
37#include "policy/policy_constants.h"
38#include "policy/proto/cloud_policy.pb.h"
39#include "testing/gtest/include/gtest/gtest.h"
40
41using testing::AnyNumber;
42using testing::AtLeast;
43using testing::Mock;
44using testing::SaveArg;
45using testing::_;
46
47namespace em = enterprise_management;
48
49namespace policy {
50
51namespace {
52
53const char kAccount1[] = "account1@localhost";
54const char kAccount2[] = "account2@localhost";
55const char kAccount3[] = "account3@localhost";
56
57const char kExtensionID[] = "kbmnembihfiondgfjekmnmcbddelicoi";
58const char kExtensionVersion[] = "1.0.0.0";
59const char kExtensionCRXPath[] = "extensions/hosted_app.crx";
60const char kUpdateURL[] = "https://clients2.google.com/service/update2/crx";
61
62}  // namespace
63
64class MockDeviceLocalAccountPolicyServiceObserver
65    : public DeviceLocalAccountPolicyService::Observer {
66 public:
67  MOCK_METHOD1(OnPolicyUpdated, void(const std::string&));
68  MOCK_METHOD0(OnDeviceLocalAccountsChanged, void(void));
69};
70
71class DeviceLocalAccountPolicyServiceTestBase
72    : public chromeos::DeviceSettingsTestBase {
73 public:
74  DeviceLocalAccountPolicyServiceTestBase();
75
76  virtual void SetUp() OVERRIDE;
77  virtual void TearDown() OVERRIDE;
78
79  void CreatePolicyService();
80
81  void InstallDeviceLocalAccountPolicy(const std::string& account_id);
82  void AddDeviceLocalAccountToPolicy(const std::string& account_id);
83  virtual void InstallDevicePolicy();
84
85  const std::string account_1_user_id_;
86  const std::string account_2_user_id_;
87
88  PolicyMap expected_policy_map_;
89  UserPolicyBuilder device_local_account_policy_;
90  chromeos::CrosSettings cros_settings_;
91  scoped_refptr<base::TestSimpleTaskRunner> extension_cache_task_runner_;
92  MockDeviceManagementService mock_device_management_service_;
93  scoped_ptr<DeviceLocalAccountPolicyService> service_;
94
95 private:
96  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyServiceTestBase);
97};
98
99class DeviceLocalAccountPolicyServiceTest
100    : public DeviceLocalAccountPolicyServiceTestBase {
101 public:
102  MOCK_METHOD1(OnRefreshDone, void(bool));
103
104 protected:
105  DeviceLocalAccountPolicyServiceTest();
106
107  virtual void SetUp() OVERRIDE;
108  virtual void TearDown() OVERRIDE;
109
110  void InstallDevicePolicy() OVERRIDE;
111
112  MockDeviceLocalAccountPolicyServiceObserver service_observer_;
113
114 private:
115  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyServiceTest);
116};
117
118DeviceLocalAccountPolicyServiceTestBase::
119    DeviceLocalAccountPolicyServiceTestBase()
120    : account_1_user_id_(GenerateDeviceLocalAccountUserId(
121          kAccount1,
122          DeviceLocalAccount::TYPE_PUBLIC_SESSION)),
123      account_2_user_id_(GenerateDeviceLocalAccountUserId(
124          kAccount2,
125          DeviceLocalAccount::TYPE_PUBLIC_SESSION)),
126      cros_settings_(&device_settings_service_),
127      extension_cache_task_runner_(new base::TestSimpleTaskRunner) {
128}
129
130void DeviceLocalAccountPolicyServiceTestBase::SetUp() {
131  chromeos::DeviceSettingsTestBase::SetUp();
132
133  // Values implicitly enforced for public accounts.
134  expected_policy_map_.Set(key::kLidCloseAction,
135                           POLICY_LEVEL_MANDATORY,
136                           POLICY_SCOPE_USER,
137                           base::Value::CreateIntegerValue(
138                               chromeos::PowerPolicyController::
139                                   ACTION_STOP_SESSION),
140                           NULL);
141  expected_policy_map_.Set(key::kShelfAutoHideBehavior,
142                           POLICY_LEVEL_MANDATORY,
143                           POLICY_SCOPE_USER,
144                           Value::CreateStringValue("Never"),
145                           NULL);
146  expected_policy_map_.Set(key::kShowLogoutButtonInTray,
147                           POLICY_LEVEL_MANDATORY,
148                           POLICY_SCOPE_USER,
149                           Value::CreateBooleanValue(true),
150                           NULL);
151  expected_policy_map_.Set(key::kFullscreenAllowed,
152                           POLICY_LEVEL_MANDATORY,
153                           POLICY_SCOPE_USER,
154                           Value::CreateBooleanValue(false),
155                           NULL);
156
157  // Explicitly set value.
158  expected_policy_map_.Set(key::kDisableSpdy,
159                           POLICY_LEVEL_MANDATORY,
160                           POLICY_SCOPE_USER,
161                           Value::CreateBooleanValue(true),
162                           NULL);
163
164  device_local_account_policy_.payload().mutable_disablespdy()->set_value(
165      true);
166  device_local_account_policy_.policy_data().set_policy_type(
167      dm_protocol::kChromePublicAccountPolicyType);
168}
169
170void DeviceLocalAccountPolicyServiceTestBase::TearDown() {
171  service_.reset();
172  extension_cache_task_runner_->RunUntilIdle();
173  chromeos::DeviceSettingsTestBase::TearDown();
174}
175
176void DeviceLocalAccountPolicyServiceTestBase::CreatePolicyService() {
177  service_.reset(new DeviceLocalAccountPolicyService(
178      &device_settings_test_helper_,
179      &device_settings_service_,
180      &cros_settings_,
181      loop_.message_loop_proxy(),
182      extension_cache_task_runner_));
183}
184
185void DeviceLocalAccountPolicyServiceTestBase::
186    InstallDeviceLocalAccountPolicy(const std::string& account_id) {
187  device_local_account_policy_.policy_data().set_settings_entity_id(account_id);
188  device_local_account_policy_.policy_data().set_username(account_id);
189  device_local_account_policy_.Build();
190  device_settings_test_helper_.set_device_local_account_policy_blob(
191      account_id, device_local_account_policy_.GetBlob());
192}
193
194void DeviceLocalAccountPolicyServiceTestBase::AddDeviceLocalAccountToPolicy(
195    const std::string& account_id) {
196  em::DeviceLocalAccountInfoProto* account =
197      device_policy_.payload().mutable_device_local_accounts()->add_account();
198  account->set_account_id(account_id);
199  account->set_type(
200      em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION);
201}
202
203void DeviceLocalAccountPolicyServiceTestBase::InstallDevicePolicy() {
204  device_policy_.Build();
205  device_settings_test_helper_.set_policy_blob(device_policy_.GetBlob());
206  ReloadDeviceSettings();
207}
208
209DeviceLocalAccountPolicyServiceTest::DeviceLocalAccountPolicyServiceTest() {
210  CreatePolicyService();
211}
212
213void DeviceLocalAccountPolicyServiceTest::SetUp() {
214  DeviceLocalAccountPolicyServiceTestBase::SetUp();
215  service_->AddObserver(&service_observer_);
216}
217
218void DeviceLocalAccountPolicyServiceTest::TearDown() {
219  service_->RemoveObserver(&service_observer_);
220  DeviceLocalAccountPolicyServiceTestBase::TearDown();
221}
222
223void DeviceLocalAccountPolicyServiceTest::InstallDevicePolicy() {
224  EXPECT_CALL(service_observer_, OnDeviceLocalAccountsChanged());
225  DeviceLocalAccountPolicyServiceTestBase::InstallDevicePolicy();
226  Mock::VerifyAndClearExpectations(&service_observer_);
227}
228
229TEST_F(DeviceLocalAccountPolicyServiceTest, NoAccounts) {
230  EXPECT_FALSE(service_->GetBrokerForUser(account_1_user_id_));
231}
232
233TEST_F(DeviceLocalAccountPolicyServiceTest, GetBroker) {
234  InstallDeviceLocalAccountPolicy(kAccount1);
235  AddDeviceLocalAccountToPolicy(kAccount1);
236  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
237  InstallDevicePolicy();
238
239  DeviceLocalAccountPolicyBroker* broker =
240      service_->GetBrokerForUser(account_1_user_id_);
241  ASSERT_TRUE(broker);
242  EXPECT_EQ(account_1_user_id_, broker->user_id());
243  ASSERT_TRUE(broker->core()->store());
244  EXPECT_EQ(CloudPolicyStore::STATUS_OK, broker->core()->store()->status());
245  EXPECT_FALSE(broker->core()->client());
246  EXPECT_FALSE(broker->core()->store()->policy_map().empty());
247}
248
249TEST_F(DeviceLocalAccountPolicyServiceTest, LoadNoPolicy) {
250  AddDeviceLocalAccountToPolicy(kAccount1);
251  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
252  InstallDevicePolicy();
253
254  DeviceLocalAccountPolicyBroker* broker =
255      service_->GetBrokerForUser(account_1_user_id_);
256  ASSERT_TRUE(broker);
257  EXPECT_EQ(account_1_user_id_, broker->user_id());
258  ASSERT_TRUE(broker->core()->store());
259  EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR,
260            broker->core()->store()->status());
261  EXPECT_TRUE(broker->core()->store()->policy_map().empty());
262  EXPECT_FALSE(service_->IsPolicyAvailableForUser(account_1_user_id_));
263}
264
265TEST_F(DeviceLocalAccountPolicyServiceTest, LoadValidationFailure) {
266  device_local_account_policy_.policy_data().set_policy_type(
267      dm_protocol::kChromeUserPolicyType);
268  InstallDeviceLocalAccountPolicy(kAccount1);
269  AddDeviceLocalAccountToPolicy(kAccount1);
270  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
271  InstallDevicePolicy();
272
273  DeviceLocalAccountPolicyBroker* broker =
274      service_->GetBrokerForUser(account_1_user_id_);
275  ASSERT_TRUE(broker);
276  EXPECT_EQ(account_1_user_id_, broker->user_id());
277  ASSERT_TRUE(broker->core()->store());
278  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR,
279            broker->core()->store()->status());
280  EXPECT_TRUE(broker->core()->store()->policy_map().empty());
281  EXPECT_FALSE(service_->IsPolicyAvailableForUser(account_1_user_id_));
282}
283
284TEST_F(DeviceLocalAccountPolicyServiceTest, LoadPolicy) {
285  InstallDeviceLocalAccountPolicy(kAccount1);
286  AddDeviceLocalAccountToPolicy(kAccount1);
287  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
288  InstallDevicePolicy();
289
290  DeviceLocalAccountPolicyBroker* broker =
291      service_->GetBrokerForUser(account_1_user_id_);
292  ASSERT_TRUE(broker);
293  EXPECT_EQ(account_1_user_id_, broker->user_id());
294  ASSERT_TRUE(broker->core()->store());
295  EXPECT_EQ(CloudPolicyStore::STATUS_OK, broker->core()->store()->status());
296  ASSERT_TRUE(broker->core()->store()->policy());
297  EXPECT_EQ(device_local_account_policy_.policy_data().SerializeAsString(),
298            broker->core()->store()->policy()->SerializeAsString());
299  EXPECT_TRUE(expected_policy_map_.Equals(
300      broker->core()->store()->policy_map()));
301  EXPECT_TRUE(service_->IsPolicyAvailableForUser(account_1_user_id_));
302}
303
304TEST_F(DeviceLocalAccountPolicyServiceTest, StoreValidationFailure) {
305  AddDeviceLocalAccountToPolicy(kAccount1);
306  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
307  InstallDevicePolicy();
308  Mock::VerifyAndClearExpectations(&service_observer_);
309
310  DeviceLocalAccountPolicyBroker* broker =
311      service_->GetBrokerForUser(account_1_user_id_);
312  ASSERT_TRUE(broker);
313  EXPECT_EQ(account_1_user_id_, broker->user_id());
314  ASSERT_TRUE(broker->core()->store());
315
316  device_local_account_policy_.policy_data().set_policy_type(
317      dm_protocol::kChromeUserPolicyType);
318  device_local_account_policy_.Build();
319  broker->core()->store()->Store(device_local_account_policy_.policy());
320  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
321  FlushDeviceSettings();
322
323  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR,
324            broker->core()->store()->status());
325  EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_WRONG_POLICY_TYPE,
326            broker->core()->store()->validation_status());
327  EXPECT_FALSE(service_->IsPolicyAvailableForUser(account_1_user_id_));
328}
329
330TEST_F(DeviceLocalAccountPolicyServiceTest, StorePolicy) {
331  AddDeviceLocalAccountToPolicy(kAccount1);
332  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
333  InstallDevicePolicy();
334  Mock::VerifyAndClearExpectations(&service_observer_);
335
336  DeviceLocalAccountPolicyBroker* broker =
337      service_->GetBrokerForUser(account_1_user_id_);
338  ASSERT_TRUE(broker);
339  EXPECT_EQ(account_1_user_id_, broker->user_id());
340  ASSERT_TRUE(broker->core()->store());
341
342  device_local_account_policy_.policy_data().set_settings_entity_id(kAccount1);
343  device_local_account_policy_.policy_data().set_username(kAccount1);
344  device_local_account_policy_.Build();
345  broker->core()->store()->Store(device_local_account_policy_.policy());
346  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
347  FlushDeviceSettings();
348
349  EXPECT_EQ(CloudPolicyStore::STATUS_OK, broker->core()->store()->status());
350  ASSERT_TRUE(broker->core()->store()->policy());
351  EXPECT_EQ(device_local_account_policy_.policy_data().SerializeAsString(),
352            broker->core()->store()->policy()->SerializeAsString());
353  EXPECT_TRUE(expected_policy_map_.Equals(
354      broker->core()->store()->policy_map()));
355  EXPECT_TRUE(service_->IsPolicyAvailableForUser(account_1_user_id_));
356}
357
358TEST_F(DeviceLocalAccountPolicyServiceTest, DevicePolicyChange) {
359  InstallDeviceLocalAccountPolicy(kAccount1);
360  AddDeviceLocalAccountToPolicy(kAccount1);
361  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
362  InstallDevicePolicy();
363
364  device_policy_.payload().mutable_device_local_accounts()->clear_account();
365  InstallDevicePolicy();
366
367  EXPECT_FALSE(service_->GetBrokerForUser(account_1_user_id_));
368}
369
370TEST_F(DeviceLocalAccountPolicyServiceTest, DuplicateAccounts) {
371  InstallDeviceLocalAccountPolicy(kAccount1);
372  AddDeviceLocalAccountToPolicy(kAccount1);
373  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
374  InstallDevicePolicy();
375  Mock::VerifyAndClearExpectations(&service_observer_);
376
377  // Add a second entry with a duplicate account name to device policy.
378  AddDeviceLocalAccountToPolicy(kAccount1);
379  InstallDevicePolicy();
380
381  // Make sure the broker is accessible and policy got loaded.
382  DeviceLocalAccountPolicyBroker* broker =
383      service_->GetBrokerForUser(account_1_user_id_);
384  ASSERT_TRUE(broker);
385  EXPECT_EQ(account_1_user_id_, broker->user_id());
386  ASSERT_TRUE(broker->core()->store());
387  EXPECT_EQ(CloudPolicyStore::STATUS_OK, broker->core()->store()->status());
388  ASSERT_TRUE(broker->core()->store()->policy());
389  EXPECT_EQ(device_local_account_policy_.policy_data().SerializeAsString(),
390            broker->core()->store()->policy()->SerializeAsString());
391  EXPECT_TRUE(expected_policy_map_.Equals(
392      broker->core()->store()->policy_map()));
393  EXPECT_TRUE(service_->IsPolicyAvailableForUser(account_1_user_id_));
394}
395
396TEST_F(DeviceLocalAccountPolicyServiceTest, FetchPolicy) {
397  InstallDeviceLocalAccountPolicy(kAccount1);
398  AddDeviceLocalAccountToPolicy(kAccount1);
399  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
400  InstallDevicePolicy();
401
402  DeviceLocalAccountPolicyBroker* broker =
403      service_->GetBrokerForUser(account_1_user_id_);
404  ASSERT_TRUE(broker);
405
406  service_->Connect(&mock_device_management_service_);
407  EXPECT_TRUE(broker->core()->client());
408
409  em::DeviceManagementRequest request;
410  em::DeviceManagementResponse response;
411  response.mutable_policy_response()->add_response()->CopyFrom(
412      device_local_account_policy_.policy());
413  EXPECT_CALL(mock_device_management_service_,
414              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
415      .WillOnce(mock_device_management_service_.SucceedJob(response));
416  EXPECT_CALL(mock_device_management_service_,
417              StartJob(dm_protocol::kValueRequestPolicy,
418                       std::string(), std::string(),
419                       device_policy_.policy_data().request_token(),
420                       dm_protocol::kValueUserAffiliationManaged,
421                       device_policy_.policy_data().device_id(),
422                       _))
423      .WillOnce(SaveArg<6>(&request));
424  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
425  broker->core()->client()->FetchPolicy();
426  FlushDeviceSettings();
427  Mock::VerifyAndClearExpectations(&service_observer_);
428  Mock::VerifyAndClearExpectations(&mock_device_management_service_);
429  EXPECT_TRUE(request.has_policy_request());
430  EXPECT_EQ(1, request.policy_request().request_size());
431  EXPECT_EQ(dm_protocol::kChromePublicAccountPolicyType,
432            request.policy_request().request(0).policy_type());
433  EXPECT_FALSE(request.policy_request().request(0).has_machine_id());
434  EXPECT_EQ(kAccount1,
435            request.policy_request().request(0).settings_entity_id());
436
437  ASSERT_TRUE(broker->core()->store());
438  EXPECT_EQ(CloudPolicyStore::STATUS_OK,
439            broker->core()->store()->status());
440  ASSERT_TRUE(broker->core()->store()->policy());
441  EXPECT_EQ(device_local_account_policy_.policy_data().SerializeAsString(),
442            broker->core()->store()->policy()->SerializeAsString());
443  EXPECT_TRUE(expected_policy_map_.Equals(
444      broker->core()->store()->policy_map()));
445  EXPECT_TRUE(service_->IsPolicyAvailableForUser(account_1_user_id_));
446
447  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_))
448      .Times(0);
449  service_->Disconnect();
450  EXPECT_FALSE(broker->core()->client());
451  Mock::VerifyAndClearExpectations(&service_observer_);
452  EXPECT_TRUE(service_->IsPolicyAvailableForUser(account_1_user_id_));
453}
454
455TEST_F(DeviceLocalAccountPolicyServiceTest, RefreshPolicy) {
456  InstallDeviceLocalAccountPolicy(kAccount1);
457  AddDeviceLocalAccountToPolicy(kAccount1);
458  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
459  InstallDevicePolicy();
460
461  DeviceLocalAccountPolicyBroker* broker =
462      service_->GetBrokerForUser(account_1_user_id_);
463  ASSERT_TRUE(broker);
464
465  service_->Connect(&mock_device_management_service_);
466  ASSERT_TRUE(broker->core()->service());
467
468  em::DeviceManagementResponse response;
469  response.mutable_policy_response()->add_response()->CopyFrom(
470      device_local_account_policy_.policy());
471  EXPECT_CALL(mock_device_management_service_, CreateJob(_))
472      .WillOnce(mock_device_management_service_.SucceedJob(response));
473  EXPECT_CALL(mock_device_management_service_, StartJob(_, _, _, _, _, _, _));
474  EXPECT_CALL(*this, OnRefreshDone(true)).Times(1);
475  EXPECT_CALL(service_observer_, OnPolicyUpdated(account_1_user_id_));
476  broker->core()->service()->RefreshPolicy(
477      base::Bind(&DeviceLocalAccountPolicyServiceTest::OnRefreshDone,
478                 base::Unretained(this)));
479  FlushDeviceSettings();
480  Mock::VerifyAndClearExpectations(&service_observer_);
481  Mock::VerifyAndClearExpectations(this);
482  Mock::VerifyAndClearExpectations(&mock_device_management_service_);
483
484  ASSERT_TRUE(broker->core()->store());
485  EXPECT_EQ(CloudPolicyStore::STATUS_OK,
486            broker->core()->store()->status());
487  EXPECT_TRUE(expected_policy_map_.Equals(
488      broker->core()->store()->policy_map()));
489  EXPECT_TRUE(service_->IsPolicyAvailableForUser(account_1_user_id_));
490}
491
492class DeviceLocalAccountPolicyExtensionCacheTest
493    : public DeviceLocalAccountPolicyServiceTestBase {
494 protected:
495  DeviceLocalAccountPolicyExtensionCacheTest();
496
497  virtual void SetUp() OVERRIDE;
498
499  base::FilePath GetCacheDirectoryForAccountID(const std::string& account_id);
500
501  base::ScopedTempDir cache_root_dir_;
502  scoped_ptr<base::ScopedPathOverride> cache_root_dir_override_;
503
504  base::FilePath cache_dir_1_;
505  base::FilePath cache_dir_2_;
506  base::FilePath cache_dir_3_;
507
508 private:
509  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyExtensionCacheTest);
510};
511
512DeviceLocalAccountPolicyExtensionCacheTest::
513    DeviceLocalAccountPolicyExtensionCacheTest() {
514}
515
516void DeviceLocalAccountPolicyExtensionCacheTest::SetUp() {
517  DeviceLocalAccountPolicyServiceTestBase::SetUp();
518  ASSERT_TRUE(cache_root_dir_.CreateUniqueTempDir());
519  cache_root_dir_override_.reset(new base::ScopedPathOverride(
520      chromeos::DIR_DEVICE_LOCAL_ACCOUNT_CACHE,
521      cache_root_dir_.path()));
522
523  cache_dir_1_ = GetCacheDirectoryForAccountID(kAccount1);
524  cache_dir_2_ = GetCacheDirectoryForAccountID(kAccount2);
525  cache_dir_3_ = GetCacheDirectoryForAccountID(kAccount3);
526
527  em::StringList* forcelist = device_local_account_policy_.payload()
528      .mutable_extensioninstallforcelist()->mutable_value();
529  forcelist->add_entries(base::StringPrintf("%s;%s", kExtensionID, kUpdateURL));
530}
531
532base::FilePath DeviceLocalAccountPolicyExtensionCacheTest::
533    GetCacheDirectoryForAccountID(const std::string& account_id) {
534  return cache_root_dir_.path().Append(base::HexEncode(account_id.c_str(),
535                                                       account_id.size()));
536}
537
538// Verifies that during startup, orphaned cache directories are deleted,
539// cache directories belonging to an existing account are preserved and missing
540// cache directories are created. Also verifies that when startup is complete,
541// the caches for all existing accounts are running.
542TEST_F(DeviceLocalAccountPolicyExtensionCacheTest, Startup) {
543  base::FilePath test_data_dir;
544  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir));
545  const base::FilePath source_crx_file =
546      test_data_dir.Append(kExtensionCRXPath);
547  const std::string target_crx_file_name =
548      base::StringPrintf("%s-%s.crx", kExtensionID, kExtensionVersion);
549
550  // Create and pre-populate a cache directory for account 1.
551  EXPECT_TRUE(file_util::CreateDirectory(cache_dir_1_));
552  EXPECT_TRUE(CopyFile(source_crx_file,
553                       cache_dir_1_.Append(target_crx_file_name)));
554
555  // Create and pre-populate a cache directory for account 3.
556  EXPECT_TRUE(file_util::CreateDirectory(cache_dir_3_));
557  EXPECT_TRUE(CopyFile(source_crx_file,
558                       cache_dir_3_.Append(target_crx_file_name)));
559
560  // Add accounts 1 and 2 to device policy.
561  InstallDeviceLocalAccountPolicy(kAccount1);
562  InstallDeviceLocalAccountPolicy(kAccount2);
563  AddDeviceLocalAccountToPolicy(kAccount1);
564  AddDeviceLocalAccountToPolicy(kAccount2);
565  InstallDevicePolicy();
566
567  // Create the DeviceLocalAccountPolicyService, allowing it to finish the
568  // deletion of orphaned cache directories.
569  CreatePolicyService();
570  FlushDeviceSettings();
571  extension_cache_task_runner_->RunUntilIdle();
572
573  // Verify that the cache directory for account 1 and its contents still exist.
574  EXPECT_TRUE(base::DirectoryExists(cache_dir_1_));
575  EXPECT_TRUE(ContentsEqual(source_crx_file,
576                            cache_dir_1_.Append(target_crx_file_name)));
577
578  // Verify that a cache directory for account 2 was created.
579  EXPECT_TRUE(base::DirectoryExists(cache_dir_2_));
580
581  // Verify that the cache directory for account 3 was deleted.
582  EXPECT_FALSE(base::DirectoryExists(cache_dir_3_));
583
584  // Verify that the cache for account 1 has been started.
585  DeviceLocalAccountPolicyBroker* broker =
586      service_->GetBrokerForUser(account_1_user_id_);
587  ASSERT_TRUE(broker);
588  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
589
590  // Verify that the cache for account 2 has been started.
591  broker = service_->GetBrokerForUser(account_2_user_id_);
592  ASSERT_TRUE(broker);
593  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
594}
595
596// Verifies that while the deletion of orphaned cache directories is in
597// progress, the caches for accounts which existed before the deletion started
598// are running but caches for newly added accounts are not started.
599TEST_F(DeviceLocalAccountPolicyExtensionCacheTest, RaceAgainstOrphanDeletion) {
600  // Add account 1 to device policy.
601  InstallDeviceLocalAccountPolicy(kAccount1);
602  AddDeviceLocalAccountToPolicy(kAccount1);
603  InstallDevicePolicy();
604
605  // Create the DeviceLocalAccountPolicyService, triggering the deletion of
606  // orphaned cache directories.
607  CreatePolicyService();
608  FlushDeviceSettings();
609
610  // Verify that the cache for account 1 has been started as it is unaffected by
611  // the orphan deletion.
612  DeviceLocalAccountPolicyBroker* broker =
613      service_->GetBrokerForUser(account_1_user_id_);
614  ASSERT_TRUE(broker);
615  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
616
617  // Add account 2 to device policy.
618  InstallDeviceLocalAccountPolicy(kAccount2);
619  AddDeviceLocalAccountToPolicy(kAccount2);
620  InstallDevicePolicy();
621
622  // Verify that the cache for account 2 has not been started yet as the orphan
623  // deletion is still in progress.
624  broker = service_->GetBrokerForUser(account_2_user_id_);
625  ASSERT_TRUE(broker);
626  EXPECT_FALSE(broker->extension_loader()->IsCacheRunning());
627
628  // Allow the orphan deletion to finish.
629  extension_cache_task_runner_->RunUntilIdle();
630  base::RunLoop().RunUntilIdle();
631
632  // Verify that the cache for account 2 has been started.
633  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
634}
635
636// Verifies that while the shutdown of a cache is in progress, no new cache is
637// started if an account with the same ID is re-added.
638TEST_F(DeviceLocalAccountPolicyExtensionCacheTest, RaceAgainstCacheShutdown) {
639  // Add account 1 to device policy.
640  InstallDeviceLocalAccountPolicy(kAccount1);
641  AddDeviceLocalAccountToPolicy(kAccount1);
642  InstallDevicePolicy();
643
644  // Create the DeviceLocalAccountPolicyService, allowing it to finish the
645  // deletion of orphaned cache directories.
646  CreatePolicyService();
647  FlushDeviceSettings();
648  extension_cache_task_runner_->RunUntilIdle();
649
650  // Remove account 1 from device policy, triggering a shutdown of its cache.
651  device_policy_.payload().mutable_device_local_accounts()->clear_account();
652  InstallDevicePolicy();
653
654  // Re-add account 1 to device policy.
655  AddDeviceLocalAccountToPolicy(kAccount1);
656  InstallDevicePolicy();
657
658  // Verify that the cache for account 1 has not been started yet as the
659  // shutdown of a previous cache for this account ID is still in progress.
660  DeviceLocalAccountPolicyBroker* broker =
661      service_->GetBrokerForUser(account_1_user_id_);
662  ASSERT_TRUE(broker);
663  EXPECT_FALSE(broker->extension_loader()->IsCacheRunning());
664
665  // Allow the cache shutdown to finish.
666  extension_cache_task_runner_->RunUntilIdle();
667  base::RunLoop().RunUntilIdle();
668
669  // Verify that the cache directory for account 1 still exists.
670  EXPECT_TRUE(base::DirectoryExists(cache_dir_1_));
671
672  // Verify that the cache for account 1 has been started, reusing the existing
673  // cache directory.
674  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
675}
676
677// Verifies that while the deletion of an obsolete cache directory is in
678// progress, no new cache is started if an account with the same ID is re-added.
679TEST_F(DeviceLocalAccountPolicyExtensionCacheTest,
680       RaceAgainstObsoleteDeletion) {
681  // Add account 1 to device policy.
682  InstallDeviceLocalAccountPolicy(kAccount1);
683  AddDeviceLocalAccountToPolicy(kAccount1);
684  InstallDevicePolicy();
685
686  // Create the DeviceLocalAccountPolicyService, allowing it to finish the
687  // deletion of orphaned cache directories.
688  CreatePolicyService();
689  FlushDeviceSettings();
690  extension_cache_task_runner_->RunUntilIdle();
691
692  // Remove account 1 from device policy, allowing the shutdown of its cache to
693  // finish and the deletion of its now obsolete cache directory to begin.
694  device_policy_.payload().mutable_device_local_accounts()->clear_account();
695  InstallDevicePolicy();
696  extension_cache_task_runner_->RunUntilIdle();
697  base::RunLoop().RunUntilIdle();
698
699  // Re-add account 1 to device policy.
700  AddDeviceLocalAccountToPolicy(kAccount1);
701  InstallDevicePolicy();
702
703  // Verify that the cache for account 1 has not been started yet as the
704  // deletion of the cache directory for this account ID is still in progress.
705  DeviceLocalAccountPolicyBroker* broker =
706      service_->GetBrokerForUser(account_1_user_id_);
707  ASSERT_TRUE(broker);
708  EXPECT_FALSE(broker->extension_loader()->IsCacheRunning());
709
710  // Allow the deletion to finish.
711  extension_cache_task_runner_->RunUntilIdle();
712  base::RunLoop().RunUntilIdle();
713
714  // Verify that the cache directory for account 1 was deleted.
715  EXPECT_FALSE(base::DirectoryExists(cache_dir_1_));
716
717  // Verify that the cache for account 1 has been started.
718  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
719}
720
721// Verifies that when an account is added and no deletion of cache directories
722// affecting this account is in progress, its cache is started immediately.
723TEST_F(DeviceLocalAccountPolicyExtensionCacheTest, AddAccount) {
724  // Create the DeviceLocalAccountPolicyService, allowing it to finish the
725  // deletion of orphaned cache directories.
726  InstallDevicePolicy();
727  CreatePolicyService();
728  FlushDeviceSettings();
729  extension_cache_task_runner_->RunUntilIdle();
730
731  // Add account 1 to device policy.
732  InstallDeviceLocalAccountPolicy(kAccount1);
733  AddDeviceLocalAccountToPolicy(kAccount1);
734  InstallDevicePolicy();
735
736  // Verify that the cache for account 1 has been started.
737  DeviceLocalAccountPolicyBroker* broker =
738      service_->GetBrokerForUser(account_1_user_id_);
739  ASSERT_TRUE(broker);
740  EXPECT_TRUE(broker->extension_loader()->IsCacheRunning());
741}
742
743// Verifies that when an account is removed, its cache directory is deleted.
744TEST_F(DeviceLocalAccountPolicyExtensionCacheTest, RemoveAccount) {
745  // Add account 1 to device policy.
746  InstallDeviceLocalAccountPolicy(kAccount1);
747  AddDeviceLocalAccountToPolicy(kAccount1);
748  InstallDevicePolicy();
749
750  // Create the DeviceLocalAccountPolicyService, allowing it to finish the
751  // deletion of orphaned cache directories.
752  CreatePolicyService();
753  FlushDeviceSettings();
754  extension_cache_task_runner_->RunUntilIdle();
755
756  // Verify that a cache directory has been created for account 1.
757  EXPECT_TRUE(base::DirectoryExists(cache_dir_1_));
758
759  // Remove account 1 from device policy, allowing the deletion of its now
760  // obsolete cache directory to finish.
761  device_policy_.payload().mutable_device_local_accounts()->clear_account();
762  InstallDevicePolicy();
763  extension_cache_task_runner_->RunUntilIdle();
764  base::RunLoop().RunUntilIdle();
765  extension_cache_task_runner_->RunUntilIdle();
766
767  // Verify that the cache directory for account 1 was deleted.
768  EXPECT_FALSE(base::DirectoryExists(cache_dir_1_));
769}
770
771class DeviceLocalAccountPolicyProviderTest
772    : public DeviceLocalAccountPolicyServiceTestBase {
773 protected:
774  DeviceLocalAccountPolicyProviderTest();
775
776  virtual void SetUp() OVERRIDE;
777  virtual void TearDown() OVERRIDE;
778
779  scoped_ptr<DeviceLocalAccountPolicyProvider> provider_;
780  MockConfigurationPolicyObserver provider_observer_;
781
782 private:
783  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyProviderTest);
784};
785
786DeviceLocalAccountPolicyProviderTest::DeviceLocalAccountPolicyProviderTest() {
787  CreatePolicyService();
788  provider_.reset(new DeviceLocalAccountPolicyProvider(
789      GenerateDeviceLocalAccountUserId(kAccount1,
790                                       DeviceLocalAccount::TYPE_PUBLIC_SESSION),
791      service_.get()));
792}
793
794void DeviceLocalAccountPolicyProviderTest::SetUp() {
795  DeviceLocalAccountPolicyServiceTestBase::SetUp();
796  provider_->Init();
797  provider_->AddObserver(&provider_observer_);
798}
799
800void DeviceLocalAccountPolicyProviderTest::TearDown() {
801  provider_->RemoveObserver(&provider_observer_);
802  provider_->Shutdown();
803  provider_.reset();
804  DeviceLocalAccountPolicyServiceTestBase::TearDown();
805}
806
807TEST_F(DeviceLocalAccountPolicyProviderTest, Initialization) {
808  EXPECT_FALSE(provider_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
809
810  // Policy change should complete initialization.
811  InstallDeviceLocalAccountPolicy(kAccount1);
812  AddDeviceLocalAccountToPolicy(kAccount1);
813  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
814      .Times(AtLeast(1));
815  InstallDevicePolicy();
816  Mock::VerifyAndClearExpectations(&provider_observer_);
817
818  EXPECT_TRUE(provider_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
819
820  // The account disappearing should *not* flip the initialization flag back.
821  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
822      .Times(AnyNumber());
823  device_policy_.payload().mutable_device_local_accounts()->clear_account();
824  InstallDevicePolicy();
825  Mock::VerifyAndClearExpectations(&provider_observer_);
826
827  EXPECT_TRUE(provider_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
828}
829
830TEST_F(DeviceLocalAccountPolicyProviderTest, Policy) {
831  // Policy should load successfully.
832  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
833      .Times(AtLeast(1));
834  InstallDeviceLocalAccountPolicy(kAccount1);
835  AddDeviceLocalAccountToPolicy(kAccount1);
836  InstallDevicePolicy();
837  Mock::VerifyAndClearExpectations(&provider_observer_);
838
839  PolicyBundle expected_policy_bundle;
840  expected_policy_bundle.Get(PolicyNamespace(
841      POLICY_DOMAIN_CHROME, std::string())).CopyFrom(expected_policy_map_);
842  EXPECT_TRUE(expected_policy_bundle.Equals(provider_->policies()));
843
844  // Policy change should be reported.
845  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
846      .Times(AtLeast(1));
847  device_local_account_policy_.payload().mutable_disablespdy()->set_value(
848      false);
849  InstallDeviceLocalAccountPolicy(kAccount1);
850  DeviceLocalAccountPolicyBroker* broker =
851      service_->GetBrokerForUser(account_1_user_id_);
852  ASSERT_TRUE(broker);
853  broker->core()->store()->Load();
854  FlushDeviceSettings();
855  Mock::VerifyAndClearExpectations(&provider_observer_);
856
857  expected_policy_bundle.Get(
858      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
859      .Set(key::kDisableSpdy,
860           POLICY_LEVEL_MANDATORY,
861           POLICY_SCOPE_USER,
862           Value::CreateBooleanValue(false),
863           NULL);
864  EXPECT_TRUE(expected_policy_bundle.Equals(provider_->policies()));
865
866  // Any values set for the |ShelfAutoHideBehavior|, |ShowLogoutButtonInTray|
867  // and |ExtensionAllowedTypes| policies should be overridden.
868  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
869      .Times(AtLeast(1));
870  device_local_account_policy_.payload().mutable_shelfautohidebehavior()->
871      set_value("Always");
872  device_local_account_policy_.payload().mutable_showlogoutbuttonintray()->
873      set_value(false);
874  InstallDeviceLocalAccountPolicy(kAccount1);
875  broker->core()->store()->Load();
876  FlushDeviceSettings();
877  Mock::VerifyAndClearExpectations(&provider_observer_);
878  EXPECT_TRUE(expected_policy_bundle.Equals(provider_->policies()));
879
880  // Account disappears, policy should stay in effect.
881  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
882      .Times(AnyNumber());
883  device_policy_.payload().mutable_device_local_accounts()->clear_account();
884  InstallDevicePolicy();
885  Mock::VerifyAndClearExpectations(&provider_observer_);
886
887  EXPECT_TRUE(expected_policy_bundle.Equals(provider_->policies()));
888}
889
890TEST_F(DeviceLocalAccountPolicyProviderTest, RefreshPolicies) {
891  // If there's no device policy, the refresh completes immediately.
892  EXPECT_FALSE(service_->GetBrokerForUser(account_1_user_id_));
893  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
894      .Times(AtLeast(1));
895  provider_->RefreshPolicies();
896  Mock::VerifyAndClearExpectations(&provider_observer_);
897
898  // Make device settings appear.
899  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
900      .Times(AnyNumber());
901  AddDeviceLocalAccountToPolicy(kAccount1);
902  InstallDevicePolicy();
903  EXPECT_TRUE(service_->GetBrokerForUser(account_1_user_id_));
904
905  // If there's no cloud connection, refreshes are still immediate.
906  DeviceLocalAccountPolicyBroker* broker =
907      service_->GetBrokerForUser(account_1_user_id_);
908  ASSERT_TRUE(broker);
909  EXPECT_FALSE(broker->core()->client());
910  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
911      .Times(AtLeast(1));
912  provider_->RefreshPolicies();
913  Mock::VerifyAndClearExpectations(&provider_observer_);
914
915  // Bring up the cloud connection. The refresh scheduler may fire refreshes at
916  // this point which are not relevant for the test.
917  EXPECT_CALL(mock_device_management_service_, CreateJob(_))
918      .WillRepeatedly(
919          mock_device_management_service_.FailJob(DM_STATUS_REQUEST_FAILED));
920  EXPECT_CALL(mock_device_management_service_, StartJob(_, _, _, _, _, _, _))
921      .Times(AnyNumber());
922  service_->Connect(&mock_device_management_service_);
923  FlushDeviceSettings();
924  Mock::VerifyAndClearExpectations(&mock_device_management_service_);
925
926  // No callbacks until the refresh completes.
927  EXPECT_CALL(provider_observer_, OnUpdatePolicy(_)).Times(0);
928  MockDeviceManagementJob* request_job;
929  EXPECT_CALL(mock_device_management_service_, CreateJob(_))
930      .WillOnce(mock_device_management_service_.CreateAsyncJob(&request_job));
931  EXPECT_CALL(mock_device_management_service_, StartJob(_, _, _, _, _, _, _));
932  provider_->RefreshPolicies();
933  ReloadDeviceSettings();
934  Mock::VerifyAndClearExpectations(&provider_observer_);
935  Mock::VerifyAndClearExpectations(&mock_device_management_service_);
936  EXPECT_TRUE(provider_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
937
938  // When the response comes in, it should propagate and fire the notification.
939  EXPECT_CALL(provider_observer_, OnUpdatePolicy(provider_.get()))
940      .Times(AtLeast(1));
941  ASSERT_TRUE(request_job);
942  em::DeviceManagementResponse response;
943  device_local_account_policy_.Build();
944  response.mutable_policy_response()->add_response()->CopyFrom(
945      device_local_account_policy_.policy());
946  request_job->SendResponse(DM_STATUS_SUCCESS, response);
947  FlushDeviceSettings();
948  Mock::VerifyAndClearExpectations(&provider_observer_);
949}
950
951}  // namespace policy
952