cloud_policy_browsertest.cc revision 868fa2fe829687343ffae624259930155e16dbd8
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 "base/command_line.h" 6#include "base/file_util.h" 7#include "base/files/file_path.h" 8#include "base/files/scoped_temp_dir.h" 9#include "base/memory/scoped_ptr.h" 10#include "base/path_service.h" 11#include "base/prefs/pref_service.h" 12#include "base/run_loop.h" 13#include "base/strings/stringprintf.h" 14#include "chrome/browser/browser_process.h" 15#include "chrome/browser/policy/browser_policy_connector.h" 16#include "chrome/browser/policy/cloud/cloud_policy_client.h" 17#include "chrome/browser/policy/cloud/cloud_policy_constants.h" 18#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h" 19#include "chrome/browser/policy/policy_map.h" 20#include "chrome/browser/policy/policy_service.h" 21#include "chrome/browser/policy/profile_policy_connector.h" 22#include "chrome/browser/policy/profile_policy_connector_factory.h" 23#include "chrome/browser/policy/test/local_policy_test_server.h" 24#include "chrome/browser/policy/test_utils.h" 25#include "chrome/browser/profiles/profile.h" 26#include "chrome/browser/ui/browser.h" 27#include "chrome/common/chrome_notification_types.h" 28#include "chrome/common/chrome_switches.h" 29#include "chrome/test/base/in_process_browser_test.h" 30#include "content/public/browser/browser_thread.h" 31#include "content/public/browser/notification_service.h" 32#include "content/public/browser/notification_source.h" 33#include "content/public/test/test_utils.h" 34#include "googleurl/src/gurl.h" 35#include "policy/policy_constants.h" 36#include "policy/proto/chrome_settings.pb.h" 37#include "policy/proto/cloud_policy.pb.h" 38#include "testing/gmock/include/gmock/gmock.h" 39#include "testing/gtest/include/gtest/gtest.h" 40 41#if defined(OS_CHROMEOS) 42#include "chrome/browser/chromeos/login/user_manager.h" 43#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" 44#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h" 45#include "chromeos/chromeos_paths.h" 46#include "chromeos/dbus/cryptohome_client.h" 47#else 48#include "chrome/browser/policy/cloud/user_cloud_policy_manager.h" 49#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h" 50#include "chrome/browser/signin/signin_manager.h" 51#include "chrome/browser/signin/signin_manager_factory.h" 52#endif 53 54using testing::AnyNumber; 55using testing::InvokeWithoutArgs; 56using testing::Mock; 57using testing::Return; 58using testing::_; 59 60namespace em = enterprise_management; 61 62namespace policy { 63 64namespace { 65 66const char* GetTestUser() { 67#if defined(OS_CHROMEOS) 68 return chromeos::UserManager::kStubUser; 69#else 70 return "user@example.com"; 71#endif 72} 73 74std::string GetEmptyPolicy() { 75 const char kEmptyPolicy[] = 76 "{" 77 " \"%s\": {" 78 " \"mandatory\": {}," 79 " \"recommended\": {}" 80 " }," 81 " \"managed_users\": [ \"*\" ]," 82 " \"policy_user\": \"%s\"," 83 " \"current_key_index\": 0" 84 "}"; 85 86 return base::StringPrintf( 87 kEmptyPolicy, dm_protocol::kChromeUserPolicyType, GetTestUser()); 88} 89 90std::string GetTestPolicy(int key_version) { 91 const char kTestPolicy[] = 92 "{" 93 " \"%s\": {" 94 " \"mandatory\": {" 95 " \"ShowHomeButton\": true," 96 " \"RestoreOnStartup\": 4," 97 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ]" 98 " }," 99 " \"recommended\": {" 100 " \"HomepageLocation\": \"google.com\"" 101 " }" 102 " }," 103 " \"managed_users\": [ \"*\" ]," 104 " \"policy_user\": \"%s\"," 105 " \"current_key_index\": %d" 106 "}"; 107 108 return base::StringPrintf(kTestPolicy, 109 dm_protocol::kChromeUserPolicyType, 110 GetTestUser(), 111 key_version); 112} 113 114void GetExpectedTestPolicy(PolicyMap* expected) { 115 expected->Set(key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 116 base::Value::CreateBooleanValue(true)); 117 expected->Set(key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, 118 POLICY_SCOPE_USER, base::Value::CreateIntegerValue(4)); 119 base::ListValue list; 120 list.AppendString("dev.chromium.org"); 121 list.AppendString("youtube.com"); 122 expected->Set( 123 key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, 124 list.DeepCopy()); 125 expected->Set( 126 key::kHomepageLocation, POLICY_LEVEL_RECOMMENDED, 127 POLICY_SCOPE_USER, base::Value::CreateStringValue("google.com")); 128} 129 130} // namespace 131 132// Tests the cloud policy stack(s). 133class CloudPolicyTest : public InProcessBrowserTest { 134 protected: 135 CloudPolicyTest() {} 136 virtual ~CloudPolicyTest() {} 137 138 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { 139 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); 140 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy())); 141 142 test_server_.reset(new LocalPolicyTestServer(policy_file_path())); 143 ASSERT_TRUE(test_server_->Start()); 144 145 std::string url = test_server_->GetServiceURL().spec(); 146 147 CommandLine* command_line = CommandLine::ForCurrentProcess(); 148 command_line->AppendSwitchASCII(switches::kDeviceManagementUrl, url); 149 } 150 151 virtual void SetUpOnMainThread() OVERRIDE { 152 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process->policy_service())) 153 << "Pre-existing policies in this machine will make this test fail."; 154 155 BrowserPolicyConnector* connector = 156 g_browser_process->browser_policy_connector(); 157 connector->ScheduleServiceInitialization(0); 158 159#if defined(OS_CHROMEOS) 160 UserCloudPolicyManagerChromeOS* policy_manager = 161 UserCloudPolicyManagerFactoryChromeOS::GetForProfile( 162 browser()->profile()); 163 ASSERT_TRUE(policy_manager); 164#else 165 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass 166 // the username to the UserCloudPolicyValidator. 167 SigninManager* signin_manager = 168 SigninManagerFactory::GetForProfile(browser()->profile()); 169 ASSERT_TRUE(signin_manager); 170 signin_manager->SetAuthenticatedUsername(GetTestUser()); 171 172 UserCloudPolicyManager* policy_manager = 173 UserCloudPolicyManagerFactory::GetForProfile(browser()->profile()); 174 ASSERT_TRUE(policy_manager); 175 policy_manager->Connect(g_browser_process->local_state(), 176 UserCloudPolicyManager::CreateCloudPolicyClient( 177 connector->device_management_service()).Pass()); 178#endif // defined(OS_CHROMEOS) 179 180 ASSERT_TRUE(policy_manager->core()->client()); 181 base::RunLoop run_loop; 182 MockCloudPolicyClientObserver observer; 183 EXPECT_CALL(observer, OnRegistrationStateChanged(_)).WillOnce( 184 InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); 185 policy_manager->core()->client()->AddObserver(&observer); 186 187 // Give a bogus OAuth token to the |policy_manager|. This should make its 188 // CloudPolicyClient fetch the DMToken. 189 ASSERT_FALSE(policy_manager->core()->client()->is_registered()); 190 em::DeviceRegisterRequest::Type registration_type = 191#if defined(OS_CHROMEOS) 192 em::DeviceRegisterRequest::USER; 193#else 194 em::DeviceRegisterRequest::BROWSER; 195#endif 196 policy_manager->core()->client()->Register( 197 registration_type, "bogus", std::string(), false, std::string()); 198 run_loop.Run(); 199 Mock::VerifyAndClearExpectations(&observer); 200 policy_manager->core()->client()->RemoveObserver(&observer); 201 EXPECT_TRUE(policy_manager->core()->client()->is_registered()); 202 203#if defined(OS_CHROMEOS) 204 // Get the path to the user policy key file. 205 base::FilePath user_policy_key_dir; 206 ASSERT_TRUE( 207 PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_policy_key_dir)); 208 std::string sanitized_username = 209 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser()); 210 user_policy_key_file_ = user_policy_key_dir.AppendASCII(sanitized_username) 211 .AppendASCII("policy.pub"); 212#endif 213 } 214 215 PolicyService* GetPolicyService() { 216 ProfilePolicyConnector* profile_connector = 217 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile()); 218 return profile_connector->policy_service(); 219 } 220 221 void SetServerPolicy(const std::string& policy) { 222 int result = file_util::WriteFile(policy_file_path(), policy.data(), 223 policy.size()); 224 ASSERT_EQ(static_cast<int>(policy.size()), result); 225 } 226 227 base::FilePath policy_file_path() const { 228 return temp_dir_.path().AppendASCII("policy.json"); 229 } 230 231 base::ScopedTempDir temp_dir_; 232 scoped_ptr<LocalPolicyTestServer> test_server_; 233 base::FilePath user_policy_key_file_; 234}; 235 236IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicy) { 237 PolicyService* policy_service = GetPolicyService(); 238 { 239 base::RunLoop run_loop; 240 // This does the initial fetch and stores the initial key. 241 policy_service->RefreshPolicies(run_loop.QuitClosure()); 242 run_loop.Run(); 243 } 244 245 PolicyMap empty; 246 EXPECT_TRUE(empty.Equals(policy_service->GetPolicies( 247 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())))); 248 249 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy(0))); 250 PolicyMap expected; 251 GetExpectedTestPolicy(&expected); 252 { 253 base::RunLoop run_loop; 254 // This fetches the new policies, using the same key. 255 policy_service->RefreshPolicies(run_loop.QuitClosure()); 256 run_loop.Run(); 257 } 258 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies( 259 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())))); 260} 261 262#if defined(OS_CHROMEOS) 263IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicyWithRotatedKey) { 264 PolicyService* policy_service = GetPolicyService(); 265 { 266 base::RunLoop run_loop; 267 // This does the initial fetch and stores the initial key. 268 policy_service->RefreshPolicies(run_loop.QuitClosure()); 269 run_loop.Run(); 270 } 271 272 // Read the initial key. 273 std::string initial_key; 274 ASSERT_TRUE( 275 file_util::ReadFileToString(user_policy_key_file_, &initial_key)); 276 277 PolicyMap empty; 278 EXPECT_TRUE(empty.Equals(policy_service->GetPolicies( 279 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())))); 280 281 // Set the new policies and a new key at the server. 282 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy(1))); 283 PolicyMap expected; 284 GetExpectedTestPolicy(&expected); 285 { 286 base::RunLoop run_loop; 287 // This fetches the new policies and does a key rotation. 288 policy_service->RefreshPolicies(run_loop.QuitClosure()); 289 run_loop.Run(); 290 } 291 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies( 292 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())))); 293 294 // Verify that the key was rotated. 295 std::string rotated_key; 296 ASSERT_TRUE( 297 file_util::ReadFileToString(user_policy_key_file_, &rotated_key)); 298 EXPECT_NE(rotated_key, initial_key); 299 300 // Another refresh using the same key won't rotate it again. 301 { 302 base::RunLoop run_loop; 303 policy_service->RefreshPolicies(run_loop.QuitClosure()); 304 run_loop.Run(); 305 } 306 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies( 307 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())))); 308 std::string current_key; 309 ASSERT_TRUE( 310 file_util::ReadFileToString(user_policy_key_file_, ¤t_key)); 311 EXPECT_EQ(rotated_key, current_key); 312} 313#endif 314 315TEST(CloudPolicyProtoTest, VerifyProtobufEquivalence) { 316 // There are 2 protobufs that can be used for user cloud policy: 317 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the 318 // version used by the server, but generates one proto message per policy; to 319 // save binary size on the client, the other version shares proto messages for 320 // policies of the same type. They generate the same bytes on the wire though, 321 // so they are compatible. This test verifies that that stays true. 322 323 // Build a ChromeSettingsProto message with one policy of each supported type. 324 em::ChromeSettingsProto chrome_settings; 325 chrome_settings.mutable_homepagelocation()->set_homepagelocation( 326 "chromium.org"); 327 chrome_settings.mutable_showhomebutton()->set_showhomebutton(true); 328 chrome_settings.mutable_restoreonstartup()->set_restoreonstartup(4); 329 em::StringList* list = 330 chrome_settings.mutable_disabledschemes()->mutable_disabledschemes(); 331 list->add_entries("ftp"); 332 list->add_entries("mailto"); 333 // Try explicitly setting a policy mode too. 334 chrome_settings.mutable_disablespdy()->set_disablespdy(false); 335 chrome_settings.mutable_disablespdy()->mutable_policy_options()->set_mode( 336 em::PolicyOptions::MANDATORY); 337 chrome_settings.mutable_syncdisabled()->set_syncdisabled(true); 338 chrome_settings.mutable_syncdisabled()->mutable_policy_options()->set_mode( 339 em::PolicyOptions::RECOMMENDED); 340 341 // Build an equivalent CloudPolicySettings message. 342 em::CloudPolicySettings cloud_policy; 343 cloud_policy.mutable_homepagelocation()->set_value("chromium.org"); 344 cloud_policy.mutable_showhomebutton()->set_value(true); 345 cloud_policy.mutable_restoreonstartup()->set_value(4); 346 list = cloud_policy.mutable_disabledschemes()->mutable_value(); 347 list->add_entries("ftp"); 348 list->add_entries("mailto"); 349 cloud_policy.mutable_disablespdy()->set_value(false); 350 cloud_policy.mutable_disablespdy()->mutable_policy_options()->set_mode( 351 em::PolicyOptions::MANDATORY); 352 cloud_policy.mutable_syncdisabled()->set_value(true); 353 cloud_policy.mutable_syncdisabled()->mutable_policy_options()->set_mode( 354 em::PolicyOptions::RECOMMENDED); 355 356 // They should now serialize to the same bytes. 357 std::string chrome_settings_serialized; 358 std::string cloud_policy_serialized; 359 ASSERT_TRUE(chrome_settings.SerializeToString(&chrome_settings_serialized)); 360 ASSERT_TRUE(cloud_policy.SerializeToString(&cloud_policy_serialized)); 361 EXPECT_EQ(chrome_settings_serialized, cloud_policy_serialized); 362} 363 364} // namespace policy 365