Home | History | Annotate | Download | only in policy
      1 // Copyright (c) 2013 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 <string>
      6 #include <vector>
      7 
      8 #include "base/basictypes.h"
      9 #include "base/bind.h"
     10 #include "base/callback.h"
     11 #include "base/command_line.h"
     12 #include "base/compiler_specific.h"
     13 #include "base/file_util.h"
     14 #include "base/files/file_path.h"
     15 #include "base/location.h"
     16 #include "base/message_loop/message_loop.h"
     17 #include "base/path_service.h"
     18 #include "base/run_loop.h"
     19 #include "chrome/browser/browser_process.h"
     20 #include "chrome/browser/chrome_notification_types.h"
     21 #include "chrome/browser/chromeos/login/user_manager.h"
     22 #include "chrome/browser/chromeos/policy/device_policy_builder.h"
     23 #include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
     24 #include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
     25 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
     26 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
     27 #include "chrome/browser/chromeos/profiles/profile_helper.h"
     28 #include "chrome/browser/chromeos/settings/device_settings_service.h"
     29 #include "chrome/browser/extensions/api/power/power_api_manager.h"
     30 #include "chrome/browser/lifetime/application_lifetime.h"
     31 #include "chrome/browser/policy/profile_policy_connector.h"
     32 #include "chrome/browser/policy/profile_policy_connector_factory.h"
     33 #include "chrome/browser/profiles/profile.h"
     34 #include "chrome/browser/profiles/profile_manager.h"
     35 #include "chrome/common/extensions/api/power.h"
     36 #include "chrome/test/base/testing_profile.h"
     37 #include "chromeos/chromeos_paths.h"
     38 #include "chromeos/chromeos_switches.h"
     39 #include "chromeos/dbus/cryptohome_client.h"
     40 #include "chromeos/dbus/fake_dbus_thread_manager.h"
     41 #include "chromeos/dbus/fake_power_manager_client.h"
     42 #include "chromeos/dbus/fake_session_manager_client.h"
     43 #include "chromeos/dbus/power_manager/policy.pb.h"
     44 #include "chromeos/dbus/power_policy_controller.h"
     45 #include "components/policy/core/common/cloud/cloud_policy_core.h"
     46 #include "components/policy/core/common/cloud/cloud_policy_store.h"
     47 #include "components/policy/core/common/cloud/policy_builder.h"
     48 #include "components/policy/core/common/external_data_fetcher.h"
     49 #include "components/policy/core/common/mock_policy_service.h"
     50 #include "components/policy/core/common/policy_service.h"
     51 #include "content/public/browser/notification_details.h"
     52 #include "content/public/browser/notification_service.h"
     53 #include "content/public/browser/notification_source.h"
     54 #include "content/public/test/test_utils.h"
     55 #include "crypto/rsa_private_key.h"
     56 #include "policy/proto/device_management_backend.pb.h"
     57 #include "testing/gmock/include/gmock/gmock.h"
     58 #include "testing/gtest/include/gtest/gtest.h"
     59 
     60 namespace em = enterprise_management;
     61 namespace pm = power_manager;
     62 
     63 using ::testing::AnyNumber;
     64 using ::testing::InvokeWithoutArgs;
     65 using ::testing::_;
     66 
     67 namespace policy {
     68 
     69 namespace {
     70 
     71 const char kLoginScreenPowerManagementPolicy[] =
     72     "{"
     73     "  \"AC\": {"
     74     "    \"Delays\": {"
     75     "      \"ScreenDim\": 5000,"
     76     "      \"ScreenOff\": 7000,"
     77     "      \"Idle\": 9000"
     78     "    },"
     79     "    \"IdleAction\": \"DoNothing\""
     80     "  },"
     81     "  \"Battery\": {"
     82     "    \"Delays\": {"
     83     "      \"ScreenDim\": 1000,"
     84     "      \"ScreenOff\": 3000,"
     85     "      \"Idle\": 4000"
     86     "    },"
     87     "    \"IdleAction\": \"DoNothing\""
     88     "  },"
     89     "  \"LidCloseAction\": \"DoNothing\","
     90     "  \"UserActivityScreenDimDelayScale\": 300"
     91     "}";
     92 
     93 }  // namespace
     94 
     95 class PowerPolicyBrowserTestBase : public DevicePolicyCrosBrowserTest {
     96  protected:
     97   PowerPolicyBrowserTestBase();
     98 
     99   // DevicePolicyCrosBrowserTest:
    100   virtual void SetUpInProcessBrowserTestFixture() OVERRIDE;
    101   virtual void SetUpOnMainThread() OVERRIDE;
    102 
    103   void InstallUserKey();
    104   void StoreAndReloadUserPolicy();
    105 
    106   void StoreAndReloadDevicePolicyAndWaitForLoginProfileChange();
    107 
    108   // Returns a string describing |policy|.
    109   std::string GetDebugString(const pm::PowerManagementPolicy& policy);
    110 
    111   UserPolicyBuilder user_policy_;
    112 
    113   chromeos::FakePowerManagerClient* power_manager_client_;
    114 
    115  private:
    116   // Runs |closure| and waits for |profile|'s user policy to be updated as a
    117   // result.
    118   void RunClosureAndWaitForUserPolicyUpdate(const base::Closure& closure,
    119                                             Profile* profile);
    120 
    121   // Reloads user policy for |profile| from session manager client.
    122   void ReloadUserPolicy(Profile* profile);
    123 
    124   DISALLOW_COPY_AND_ASSIGN(PowerPolicyBrowserTestBase);
    125 };
    126 
    127 class PowerPolicyLoginScreenBrowserTest : public PowerPolicyBrowserTestBase {
    128  protected:
    129   PowerPolicyLoginScreenBrowserTest();
    130 
    131   // PowerPolicyBrowserTestBase:
    132   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE;
    133   virtual void SetUpOnMainThread() OVERRIDE;
    134   virtual void CleanUpOnMainThread() OVERRIDE;
    135 
    136   DISALLOW_COPY_AND_ASSIGN(PowerPolicyLoginScreenBrowserTest);
    137 };
    138 
    139 class PowerPolicyInSessionBrowserTest : public PowerPolicyBrowserTestBase {
    140  protected:
    141   PowerPolicyInSessionBrowserTest();
    142 
    143   // PowerPolicyBrowserTestBase:
    144   virtual void SetUpOnMainThread() OVERRIDE;
    145 
    146   DISALLOW_COPY_AND_ASSIGN(PowerPolicyInSessionBrowserTest);
    147 };
    148 
    149 PowerPolicyBrowserTestBase::PowerPolicyBrowserTestBase()
    150     : power_manager_client_(NULL) {
    151 }
    152 
    153 void PowerPolicyBrowserTestBase::SetUpInProcessBrowserTestFixture() {
    154   power_manager_client_ = new chromeos::FakePowerManagerClient;
    155   fake_dbus_thread_manager()->SetPowerManagerClient(
    156       scoped_ptr<chromeos::PowerManagerClient>(power_manager_client_));
    157 
    158   DevicePolicyCrosBrowserTest::SetUpInProcessBrowserTestFixture();
    159 
    160   // Initialize device policy.
    161   InstallOwnerKey();
    162   MarkAsEnterpriseOwned();
    163 }
    164 
    165 void PowerPolicyBrowserTestBase::SetUpOnMainThread() {
    166   DevicePolicyCrosBrowserTest::SetUpOnMainThread();
    167 
    168   // Initialize user policy.
    169   InstallUserKey();
    170   user_policy_.policy_data().set_username(chromeos::UserManager::kStubUser);
    171 }
    172 
    173 void PowerPolicyBrowserTestBase::InstallUserKey() {
    174   base::FilePath user_keys_dir;
    175   ASSERT_TRUE(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_keys_dir));
    176   std::string sanitized_username =
    177       chromeos::CryptohomeClient::GetStubSanitizedUsername(
    178           chromeos::UserManager::kStubUser);
    179   base::FilePath user_key_file =
    180       user_keys_dir.AppendASCII(sanitized_username)
    181                    .AppendASCII("policy.pub");
    182   std::vector<uint8> user_key_bits;
    183   ASSERT_TRUE(user_policy_.GetSigningKey()->ExportPublicKey(&user_key_bits));
    184   ASSERT_TRUE(base::CreateDirectory(user_key_file.DirName()));
    185   ASSERT_EQ(file_util::WriteFile(
    186                 user_key_file,
    187                 reinterpret_cast<const char*>(user_key_bits.data()),
    188                 user_key_bits.size()),
    189             static_cast<int>(user_key_bits.size()));
    190 }
    191 
    192 void PowerPolicyBrowserTestBase::StoreAndReloadUserPolicy() {
    193   ProfileManager* profile_manager = g_browser_process->profile_manager();
    194   Profile* profile = profile_manager->GetProfileByPath(
    195       profile_manager->user_data_dir().Append(
    196           TestingProfile::kTestUserProfileDir));
    197   ASSERT_TRUE(profile);
    198 
    199   // Install the new user policy blob in session manager client.
    200   user_policy_.Build();
    201   session_manager_client()->set_user_policy(
    202       user_policy_.policy_data().username(),
    203       user_policy_.GetBlob());
    204 
    205   // Reload user policy from session manager client and wait for the update to
    206   // take effect.
    207   RunClosureAndWaitForUserPolicyUpdate(
    208       base::Bind(&PowerPolicyBrowserTestBase::ReloadUserPolicy, this, profile),
    209       profile);
    210 }
    211 
    212 void PowerPolicyBrowserTestBase::
    213     StoreAndReloadDevicePolicyAndWaitForLoginProfileChange() {
    214   Profile* profile = chromeos::ProfileHelper::GetSigninProfile();
    215   ASSERT_TRUE(profile);
    216 
    217   // Install the new device policy blob in session manager client, reload device
    218   // policy from session manager client and wait for a change in the login
    219   // profile's policy to be observed.
    220   RunClosureAndWaitForUserPolicyUpdate(
    221       base::Bind(&PowerPolicyBrowserTestBase::RefreshDevicePolicy, this),
    222       profile);
    223 }
    224 
    225 std::string PowerPolicyBrowserTestBase::GetDebugString(
    226     const pm::PowerManagementPolicy& policy) {
    227   return chromeos::PowerPolicyController::GetPolicyDebugString(policy);
    228 }
    229 
    230 void PowerPolicyBrowserTestBase::RunClosureAndWaitForUserPolicyUpdate(
    231     const base::Closure& closure,
    232     Profile* profile) {
    233   base::RunLoop run_loop;
    234   MockPolicyServiceObserver observer;
    235   EXPECT_CALL(observer, OnPolicyUpdated(_, _, _))
    236       .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
    237   EXPECT_CALL(observer, OnPolicyServiceInitialized(_)).Times(AnyNumber());
    238   PolicyService* policy_service =
    239       ProfilePolicyConnectorFactory::GetForProfile(profile)->policy_service();
    240   ASSERT_TRUE(policy_service);
    241   policy_service->AddObserver(POLICY_DOMAIN_CHROME, &observer);
    242   closure.Run();
    243   run_loop.Run();
    244   policy_service->RemoveObserver(POLICY_DOMAIN_CHROME, &observer);
    245 }
    246 
    247 void PowerPolicyBrowserTestBase::ReloadUserPolicy(Profile* profile) {
    248   UserCloudPolicyManagerChromeOS* policy_manager =
    249       UserCloudPolicyManagerFactoryChromeOS::GetForProfile(profile);
    250   ASSERT_TRUE(policy_manager);
    251   policy_manager->core()->store()->Load();
    252 }
    253 
    254 PowerPolicyLoginScreenBrowserTest::PowerPolicyLoginScreenBrowserTest() {
    255 }
    256 
    257 void PowerPolicyLoginScreenBrowserTest::SetUpCommandLine(
    258     CommandLine* command_line) {
    259   PowerPolicyBrowserTestBase::SetUpCommandLine(command_line);
    260   command_line->AppendSwitch(chromeos::switches::kLoginManager);
    261   command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests);
    262 }
    263 
    264 void PowerPolicyLoginScreenBrowserTest::SetUpOnMainThread() {
    265   PowerPolicyBrowserTestBase::SetUpOnMainThread();
    266 
    267   // Wait for the login screen to be shown.
    268   content::WindowedNotificationObserver(
    269       chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
    270       content::NotificationService::AllSources()).Wait();
    271 }
    272 
    273 void PowerPolicyLoginScreenBrowserTest::CleanUpOnMainThread() {
    274   base::MessageLoop::current()->PostTask(FROM_HERE,
    275                                          base::Bind(&chrome::AttemptExit));
    276   base::RunLoop().RunUntilIdle();
    277   PowerPolicyBrowserTestBase::CleanUpOnMainThread();
    278 }
    279 
    280 PowerPolicyInSessionBrowserTest::PowerPolicyInSessionBrowserTest() {
    281 }
    282 
    283 void PowerPolicyInSessionBrowserTest::SetUpOnMainThread() {
    284   PowerPolicyBrowserTestBase::SetUpOnMainThread();
    285 
    286   // Tell the DeviceSettingsService that there is no local owner.
    287   chromeos::DeviceSettingsService::Get()->SetUsername(std::string());
    288 }
    289 
    290 // Verifies that device policy is applied on the login screen.
    291 IN_PROC_BROWSER_TEST_F(PowerPolicyLoginScreenBrowserTest, SetDevicePolicy) {
    292   pm::PowerManagementPolicy power_management_policy =
    293       power_manager_client_->get_policy();
    294   power_management_policy.mutable_ac_delays()->set_screen_dim_ms(5000);
    295   power_management_policy.mutable_ac_delays()->set_screen_off_ms(7000);
    296   power_management_policy.mutable_ac_delays()->set_idle_ms(9000);
    297   power_management_policy.mutable_battery_delays()->set_screen_dim_ms(1000);
    298   power_management_policy.mutable_battery_delays()->set_screen_off_ms(3000);
    299   power_management_policy.mutable_battery_delays()->set_idle_ms(4000);
    300   power_management_policy.set_ac_idle_action(
    301       pm::PowerManagementPolicy::DO_NOTHING);
    302   power_management_policy.set_battery_idle_action(
    303       pm::PowerManagementPolicy::DO_NOTHING);
    304   power_management_policy.set_lid_closed_action(
    305       pm::PowerManagementPolicy::DO_NOTHING);
    306   power_management_policy.set_user_activity_screen_dim_delay_factor(3.0);
    307 
    308   em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
    309   proto.mutable_login_screen_power_management()->
    310       set_login_screen_power_management(kLoginScreenPowerManagementPolicy);
    311   StoreAndReloadDevicePolicyAndWaitForLoginProfileChange();
    312   EXPECT_EQ(GetDebugString(power_management_policy),
    313             GetDebugString(power_manager_client_->get_policy()));
    314 }
    315 
    316 // Verifies that device policy is ignored during a session.
    317 IN_PROC_BROWSER_TEST_F(PowerPolicyInSessionBrowserTest, SetDevicePolicy) {
    318   pm::PowerManagementPolicy power_management_policy =
    319       power_manager_client_->get_policy();
    320 
    321   em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
    322   proto.mutable_login_screen_power_management()->
    323       set_login_screen_power_management(kLoginScreenPowerManagementPolicy);
    324   StoreAndReloadDevicePolicyAndWaitForLoginProfileChange();
    325   EXPECT_EQ(GetDebugString(power_management_policy),
    326             GetDebugString(power_manager_client_->get_policy()));
    327 }
    328 
    329 // Verifies that user policy is applied during a session.
    330 IN_PROC_BROWSER_TEST_F(PowerPolicyInSessionBrowserTest, SetUserPolicy) {
    331   pm::PowerManagementPolicy power_management_policy =
    332       power_manager_client_->get_policy();
    333   power_management_policy.mutable_ac_delays()->set_screen_dim_ms(5000);
    334   power_management_policy.mutable_ac_delays()->set_screen_lock_ms(6000);
    335   power_management_policy.mutable_ac_delays()->set_screen_off_ms(7000);
    336   power_management_policy.mutable_ac_delays()->set_idle_warning_ms(8000);
    337   power_management_policy.mutable_ac_delays()->set_idle_ms(9000);
    338   power_management_policy.mutable_battery_delays()->set_screen_dim_ms(1000);
    339   power_management_policy.mutable_battery_delays()->set_screen_lock_ms(2000);
    340   power_management_policy.mutable_battery_delays()->set_screen_off_ms(3000);
    341   power_management_policy.mutable_battery_delays()->set_idle_warning_ms(4000);
    342   power_management_policy.mutable_battery_delays()->set_idle_ms(5000);
    343   power_management_policy.set_use_audio_activity(false);
    344   power_management_policy.set_use_video_activity(false);
    345   power_management_policy.set_ac_idle_action(
    346       pm::PowerManagementPolicy::STOP_SESSION);
    347   power_management_policy.set_battery_idle_action(
    348       pm::PowerManagementPolicy::STOP_SESSION);
    349   power_management_policy.set_lid_closed_action(
    350       pm::PowerManagementPolicy::STOP_SESSION);
    351   power_management_policy.set_presentation_screen_dim_delay_factor(3.0);
    352   power_management_policy.set_user_activity_screen_dim_delay_factor(3.0);
    353   power_management_policy.set_wait_for_initial_user_activity(true);
    354 
    355   user_policy_.payload().mutable_screendimdelayac()->set_value(5000);
    356   user_policy_.payload().mutable_screenlockdelayac()->set_value(6000);
    357   user_policy_.payload().mutable_screenoffdelayac()->set_value(7000);
    358   user_policy_.payload().mutable_idlewarningdelayac()->set_value(8000);
    359   user_policy_.payload().mutable_idledelayac()->set_value(9000);
    360   user_policy_.payload().mutable_screendimdelaybattery()->set_value(1000);
    361   user_policy_.payload().mutable_screenlockdelaybattery()->set_value(2000);
    362   user_policy_.payload().mutable_screenoffdelaybattery()->set_value(3000);
    363   user_policy_.payload().mutable_idlewarningdelaybattery()->set_value(4000);
    364   user_policy_.payload().mutable_idledelaybattery()->set_value(5000);
    365   user_policy_.payload().mutable_powermanagementusesaudioactivity()->set_value(
    366       false);
    367   user_policy_.payload().mutable_powermanagementusesvideoactivity()->set_value(
    368       false);
    369   user_policy_.payload().mutable_idleactionac()->set_value(
    370       chromeos::PowerPolicyController::ACTION_STOP_SESSION);
    371   user_policy_.payload().mutable_idleactionbattery()->set_value(
    372       chromeos::PowerPolicyController::ACTION_STOP_SESSION);
    373   user_policy_.payload().mutable_lidcloseaction()->set_value(
    374       chromeos::PowerPolicyController::ACTION_STOP_SESSION);
    375   user_policy_.payload().mutable_presentationscreendimdelayscale()->set_value(
    376       300);
    377   user_policy_.payload().mutable_useractivityscreendimdelayscale()->set_value(
    378       300);
    379   user_policy_.payload().mutable_waitforinitialuseractivity()->set_value(true);
    380   StoreAndReloadUserPolicy();
    381   EXPECT_EQ(GetDebugString(power_management_policy),
    382             GetDebugString(power_manager_client_->get_policy()));
    383 }
    384 
    385 // Verifies that screen wake locks can be enabled and disabled by extensions and
    386 // user policy during a session.
    387 IN_PROC_BROWSER_TEST_F(PowerPolicyInSessionBrowserTest, AllowScreenWakeLocks) {
    388   pm::PowerManagementPolicy baseline_policy =
    389       power_manager_client_->get_policy();
    390 
    391   // Default settings should have delays.
    392   pm::PowerManagementPolicy power_management_policy = baseline_policy;
    393   EXPECT_NE(0, baseline_policy.ac_delays().screen_dim_ms());
    394   EXPECT_NE(0, baseline_policy.ac_delays().screen_off_ms());
    395   EXPECT_NE(0, baseline_policy.battery_delays().screen_dim_ms());
    396   EXPECT_NE(0, baseline_policy.battery_delays().screen_off_ms());
    397 
    398   // Pretend an extension grabs a screen wake lock.
    399   const char kExtensionId[] = "abcdefghijklmnopabcdefghijlkmnop";
    400   extensions::PowerApiManager::GetInstance()->AddRequest(
    401       kExtensionId, extensions::api::power::LEVEL_DISPLAY);
    402   base::RunLoop().RunUntilIdle();
    403 
    404   // Check that the lock is in effect (ignoring ac_idle_action,
    405   // battery_idle_action and reason).
    406   pm::PowerManagementPolicy policy = baseline_policy;
    407   policy.mutable_ac_delays()->set_screen_dim_ms(0);
    408   policy.mutable_ac_delays()->set_screen_off_ms(0);
    409   policy.mutable_battery_delays()->set_screen_dim_ms(0);
    410   policy.mutable_battery_delays()->set_screen_off_ms(0);
    411   policy.set_ac_idle_action(
    412       power_manager_client_->get_policy().ac_idle_action());
    413   policy.set_battery_idle_action(
    414       power_manager_client_->get_policy().battery_idle_action());
    415   policy.set_reason(power_manager_client_->get_policy().reason());
    416   EXPECT_EQ(GetDebugString(policy),
    417             GetDebugString(power_manager_client_->get_policy()));
    418 
    419   // Engage the user policy and verify that the defaults take effect again.
    420   user_policy_.payload().mutable_allowscreenwakelocks()->set_value(false);
    421   StoreAndReloadUserPolicy();
    422   policy = baseline_policy;
    423   policy.set_ac_idle_action(
    424       power_manager_client_->get_policy().ac_idle_action());
    425   policy.set_battery_idle_action(
    426       power_manager_client_->get_policy().battery_idle_action());
    427   policy.set_reason(power_manager_client_->get_policy().reason());
    428   EXPECT_EQ(GetDebugString(policy),
    429             GetDebugString(power_manager_client_->get_policy()));
    430 }
    431 
    432 }  // namespace policy
    433